2011-09-03 20 views
2

我有一個自定義ChangeUserForm(用戶的ModelForm),允許用戶更新他們的帳戶信息。Django自定義ChangeUserForm設置is_active,is_staff和is_superuser爲False

然而,當我保存表單, user.is_active user.is_staff user.is_superuser都得到設爲

想到這裏發生了什麼?

forms.py

class UserChangeForm(forms.ModelForm): 
    username = forms.RegexField(label="Username", max_length=30, regex=r'^[\[email protected]+-]+$', 
     help_text = "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.", 
     error_messages = {'invalid': "This value may contain only letters, numbers and @/./+/-/_ characters."}) 
    first_name = forms.CharField(label="First name", max_length=30) 
    last_name = forms.CharField(label="Last name", max_length=30) 
    email = forms.EmailField(label="E-mail Address") 
    new_password1 = forms.CharField(label="New password", widget=forms.PasswordInput, required=False) 
    new_password2 = forms.CharField(label="Confirm new password", widget=forms.PasswordInput, required=False) 

    class Meta(auth_forms.UserChangeForm): 
     model = User 
     exclude = ('password', 'last_login', 'date_joined') 

    def clean_new_password2(self): 
     password1 = self.cleaned_data.get('new_password1') 
     password2 = self.cleaned_data.get('new_password2') 

     if password1 != password2: 
      raise forms.ValidationError("The two password fields didn't match.") 
     else: 
      if len(password2) > 0 and len(password2) < 8: 
       raise forms.ValidationError("Your password must be a minimum of 8 characters.") 
     return password2 

    def save(self, commit=True): 
     user = super(UserChangeForm, self).save(commit=False) 
     if len(self.cleaned_data['new_password2']) > 0: 
      user.set_password(self.cleaned_data['new_password2']) 
     if commit: 
      user.save() 
     return user 

    class UserProfileForm(forms.ModelForm): 
     class Meta: 
      model = UserProfile 
      exclude = ('user') 

views.py

@login_required 
def profile(request): 
    context = {} 
    if request.method == 'POST': 
     user_form = UserChangeForm(request.POST, instance = request.user) 
     user_profile_form = UserProfileForm(request.POST, instance = request.user.profile) 
     if user_form.is_valid() and user_profile_form.is_valid(): 
      user_form.save() 
      user_profile_form.save() 

      return render_to_response('accounts_profile_complete.html', context_instance=RequestContext(request)) 
    else: 
     user_form = UserChangeForm(instance = request.user) 
     user_profile_form = UserProfileForm(instance = request.user.profile) 
    context.update(csrf(request)) 
    context['user_form'] = user_form 
    context['user_profile_form'] = user_profile_form 

    return render_to_response('accounts_profile.html', context, context_instance=RequestContext(request)) 

回答

2

只是一個猜測:他們是不是在Meta類的排除列表中,這樣他們正在設置爲false(布爾字段類似於那些使用複選框,未選中時不會顯示在POST數據中)。表單不能區分設置爲false的布爾表單字段和不在頁面上的布爾表單字段之間的區別,因此您需要明確排除它們。

+0

啊,當然!謝謝! –

相關問題