Django 自定义 ChangeUserForm 将 is_active、is_staff 和 is_superuser 设置为 False

发布于 2024-12-02 23:22:54 字数 2915 浏览 0 评论 0原文

我有一个自定义的 ChangeUserForm(用户的 ModelForm),允许用户更新其帐户信息。

但是,当我保存表单时,user.is_activeuser.is_staffuser.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

☆獨立☆ 2024-12-09 23:22:54

只是猜测:它们不在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文