我想在用户admin add和中创建所需的电子邮件字段 改变页面。我读过这篇文章: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.
当我尝试从更改屏幕保存时,它会显示“请更正 下面的错误。“即使没有显示错误。
如何在更改表单中解决这些问题?
答案 0 :(得分:10)
查看source code of the UserAdmin。
UserAdmin使用UserChangeForm
作为form
属性,使用UserCreationForm
作为add_form
属性。但是你已经使用派生自UserCreationForm
的类来覆盖它们,这对于创建视图是可以的,但对于更新视图不起作用。
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)
这应该可以解决问题。