9

我正在使用 Django 1.5 和 Python 3.2.3。

我有一个自定义身份验证设置,它使用电子邮件地址而不是用户名。模型中根本没有定义用户名。这很好用。然而,当我构建一个用户创建表单时,它无论如何都会添加一个用户名字段。所以我尝试准确定义我想要显示的字段,但它仍然强制用户名字段进入表单......即使它甚至不存在于自定义身份验证模型中。我怎样才能让它停止这样做?

我的表格是这样定义的:

class UserCreateForm(UserCreationForm):

    class Meta:
        model = MyUsr
        fields = ('email','fname','surname','password1','password2',
                  'activation_code','is_active')

在文档中,自定义用户和内置表单说它“必须为任何自定义用户模型重新编写”。我认为这就是我在这里所做的。不过,无论是 this 还是UserCreationForm 文档都没有对此进行更多说明。所以我不知道我错过了什么。我也没有通过谷歌找到任何东西。

4

2 回答 2

15

UserCreationForm应该看起来像

# forms.py
from .models import CustomUser

class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput)

    class Meta:
        model = CustomUserModel
        # Note - include all *required* CustomUser fields here,
        # but don't need to include password1 and password2 as they are
        # already included since they are defined above.
        fields = ("email",)

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            msg = "Passwords don't match"
            raise forms.ValidationError("Password mismatch")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

您还需要一个不会覆盖密码字段的用户更改表单:

class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = CustomUser

    def clean_password(self):
        # always return the initial value
        return self.initial['password']

在您的管理员中定义这些,如下所示:

#admin.py

from .forms import UserChangeForm, UserAddForm

class CustomUserAdmin(UserAdmin):
    add_form = UserCreationForm
    form = UserChangeForm

您还需要覆盖list_display, list_filter, search_fields, ordering, filter_horizontal, fieldsets, and add_fieldsetsdjango.contrib.auth.admin.UserAdmin其中提到的所有内容username,我想我都列出了所有内容)。

于 2013-05-15T16:47:43.180 回答
4

您需要从 sctratch 创建表单,它不应该扩展 UserCreationForm。UserCreationForm 具有明确定义的用户名字段以及其他一些字段。你可以看看这里

于 2013-05-15T11:01:44.863 回答