gpt4 book ai didi

django - 如何使 django 用户管理中的电子邮件字段成为必需

转载 作者:行者123 更新时间:2023-12-01 07:24:29 24 4
gpt4 key购买 nike

我想让用户管理员中所需的电子邮件字段添加和
更改页面。我读了这篇文章:Django User model email field: how to make it mandatory我这样做了:

class MyUserCreationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(MyUserCreationForm, self).__init__(*args, **kwargs)
# make user email field required
self.fields['email'].required = True

class UserAdmin(BaseUserAdmin):
form = MyUserCreationForm
add_form = MyUserCreationForm
add_fieldsets = ((None, {'fields': ('username', 'email',
'password1', 'password2'), 'classes': ('wide',)}),)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

这在添加用户中工作正常,但在更改用户中我得到用户的
密码字段中显示的加密密码,而不是您的密码
通常见:
algorithm: pbkdf2_sha256 iterations: 24000 salt: ****** hash:
**************************************
Raw passwords are not stored, so there is no way to see this user's
password, but you can change the password using this form.

当我尝试从更改屏幕保存时,它说“请更正
下面的错误。”即使没有显示错误。

如何在更改表单中解决这些问题?

最佳答案

看看 source code of the UserAdmin .

UserAdmin 使用 UserChangeForm照原样 form属性(property)和UserCreationForm照原样 add_form属性(property)。但是您已经使用派生自 UserCreationForm 的类覆盖了它们。这对创建 View 没问题,但不适用于更新 View 。

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User

class EmailRequiredMixin(object):
def __init__(self, *args, **kwargs):
super(EmailRequiredMixin, self).__init__(*args, **kwargs)
# make user email field required
self.fields['email'].required = True


class MyUserCreationForm(EmailRequiredMixin, UserCreationForm):
pass


class MyUserChangeForm(EmailRequiredMixin, UserChangeForm):
pass


class EmailRequiredUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
add_fieldsets = ((None, {
'fields': ('username', 'email', 'password1', 'password2'),
'classes': ('wide',)
}),)

admin.site.unregister(User)
admin.site.register(User, EmailRequiredUserAdmin)

这应该可以解决问题。

关于django - 如何使 django 用户管理中的电子邮件字段成为必需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com