Django 自定义 ChangeUserForm 将 is_active、is_staff 和 is_superuser 设置为 False
我有一个自定义的 ChangeUserForm(用户的 ModelForm),允许用户更新其帐户信息。
但是,当我保存表单时,user.is_active、user.is_staff 和 user.is_superuser 全部设置为False.
对这里发生的事情有什么想法吗?
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))
I have a custom ChangeUserForm (ModelForm on User) that allows a user to update their account information.
However, when I save the form, user.is_active, user.is_staff and user.is_superuser all get set to False.
Any thoughts on what's going on here?
forms.py
class UserChangeForm(forms.ModelForm):
username = forms.RegexField(label="Username", max_length=30, regex=r'^[\w.@+-]+
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))
,
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是猜测:它们不在
Meta
类中的排除列表中,因此它们被设置为 false(像这样的布尔字段使用复选框,当未选中)。该表单无法区分设置为 false 的布尔表单字段和一开始不在页面上的布尔表单字段,因此您需要显式排除它们。Just a guess: they aren't on the exclusion list in the
Meta
class so they're being set to false (boolean fields like those use a checkbox, which doesn't show up in POST data when unchecked). The form can't tell the difference between a boolean form field set to false and one that isn't on the page in the first place so you need to explicitly exclude them.