2017-10-18 9 views
0

User 모델에 대해 UpdateView UpdateAccountView을 쓰고 있습니다. 새 사용자 생성에 이미 사용 된 ModelForm MyUserCreationForm을 통해 업데이트합니다. 문제는 Submit을 클릭하여 템플릿의 변경 사항을 저장할 때마다 템플릿을 다시 렌더링한다는 것입니다.Django UpdateView는 ModelForm을 사용하여 신규 사용자 또는 기존 사용자가 저장하지 않음

예를 들어 필드를 변경하지 않은 경우 "사용자 이름이 이미 사용되었습니다"라는 오류 메시지가 표시되어 MyUserCreationForm에서 고유 한 사용자 이름을 확인하거나 새 항목에 대한 템플릿을 다시 렌더링합니다. 모델에 실제로 변경 사항을 저장하지 않고도 필드를 수정할 수 있습니다. 여기

MyUserCreationForm

class MyUserCreationForm(UserCreationForm): 

    class Meta: 
     model = User #extended from auth.models.User 
     fields = ("first_name", "last_name", "username", "email", "gender", "profile_photo") 

    # adding bootstrap styling to the ModelForm fields 
    def __init__(self, *args, **kwargs): 
     super(MyUserCreationForm, self).__init__(*args, **kwargs) 
     for field in iter(self.fields): 
      self.fields[field].widget.attrs.update({ 
       'class': 'form-control input-lg', 
       'placeholder': field.replace("_", " ").title(), 
       'tabindex': list(self.fields).index(field) + 1}) 
      self.fields[field].widget.attrs.pop('autofocus', None) 

      if field == 'username' or field == 'email': 
       self.fields[field].widget.attrs.update({ 
        'placeholder': field.replace("_", " ").title() + ' *', 
       }) 


    def clean_username(self): 

     username = self.cleaned_data['username'] 
     if not re.search(r'^[\w.-]+$', username): 
      raise forms.ValidationError('Username can only contain alphanumeric characters, dots, hyphens ,and underscores') 
     try: 
      User.objects.get(username=username) 
     except ObjectDoesNotExist: 
      return username 
     raise forms.ValidationError('Username is already taken.') 

이며, 여기에 내가 직접 UpdateView에서 모델과 필드를 사용하여 모델을 업데이트 할 경우 UpdateAccountView

class UpdateAccountView(UpdateView): 
    form_class = MyUserCreationForm 
    model = User 
    template_name = 'auth/account-edit.html' 
    success_url = '/' 

    def get_object(self, queryset=None): 
     return self.request.user 

그러나, 그것은 작동하는 뷰 클래스를하다 벌금. 그러나 렌더링 할 때 스타일을 제어하려면 ModelForm을 통해 처리해야합니다.

그래서 문제가 ModelForm 안에 있다는 것을 압니다.하지만 많은 것을 검색 한 후에도 찾을 수 없습니다.

미리 감사드립니다.

+0

개체를 업데이트하는 데 생성 양식을 사용하는 것이 실제로 의미가 없습니다. 특히,'UserCreation' 폼은 비밀번호를 설정하는 코드를 가지고 있습니다. 문제가 발생할 수 있습니다. 템플릿을 스타일링하는 코드를 별도의 믹스 인으로 분해하는 것이 더 좋습니다. – Alasdair

+0

만약 내가 알았다면 나는이 옵션으로 가고 싶다. 제 말은 ModelForm'init' 위젯에서 스타일을 분리하는 것이 더 낫다는 것을 의미합니다. mixin에서 modelform을 스타일링하는 방법을 알려주십시오. – Khaled

+0

"다른 코드"가 무엇인지 모르겠다. – Alasdair

답변

0

은 별도의 믹스 인에의 필드 스타일의 코드 이동을 시도 할 수 :

class UserStyleMixin(object): 
    def __init__(self, *args, **kwargs): 
     super(UserStyleMixin, self).__init__(*args, **kwargs) 
     # Style the fields here 

그런 다음 당신은 당신의 MyUserCreationForm이 믹스 인을 사용 할 수 있습니다, 그리고 업데이트 뷰에 대한 새 양식을 만듭니다. 업데이트 뷰는 사용자가 사용자 이름을 변경할 수 있다면, 당신은 여전히 ​​사용자 이름이 허용 독특한되어 있는지 확인해야

class MyUserCreationForm(UserStyleMixin, UserCreationForm): 
    ... 

class UserUpdateForm(UserStyleMixin, forms.ModelForm): 
    ... 

참고. 모델에 사용자 이름이 unique=True이라면 장고가 이것을 처리해야합니다. 사용자 이름 정규식을 모델로 옮기는 것도 좋은 생각입니다.

+1

아주 좋습니다! 네, 저는 updateview를위한 새로운 ModelForm을 만들었고 이제는 잘 작동합니다. 나는 또한 믹스 인을했다. BTW, 내'User' 모델은 django'AbstractUser'에서 상속을받습니다. 멋진 기능이 이미 고유성과 정확성을 검사하도록 설정되어 있습니다. 내가 전체'clean_username' 함수를 제거하고 나는 장고가 처리하도록했다. 답변 해 주셔서 감사합니다. – Khaled