如何在django用户admin中创建电子邮件字段

时间:2017-01-31 21:16:43

标签: django django-admin

我想在用户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.

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

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

1 个答案:

答案 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)

这应该可以解决问题。