我有一个自定义的ChangeUserForm(ModelForm on User),允许用户更新他们的帐户信息。
但是,当我保存表单时, 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'^[\w.@+-]+$',
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))
答案 0 :(得分:2)
只是猜测:它们不在Meta
类的排除列表中,因此它们被设置为false(布尔字段就像那些使用复选框一样,当POST数据中没有显示时)未选中)。表单无法区分设置为false的布尔表单字段与首先不在页面上的字段,因此您需要明确地排除它们。