Django 1.5:UserCreationForm&自定义身份验证模型

时间:2013-05-15 10:22:59

标签: django django-models python-3.x django-forms

我正在使用Django 1.5& Python 3.2.3。

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

我的表格定义如下:

class UserCreateForm(UserCreationForm):

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

在文档中,Custom Users and Builtin Forms表示“必须为任何自定义用户模型重写”。而我认为这就是我在这里所做的。尽管如此,这个和UserCreationForm documentation都没有更多地说这个。所以我不知道我错过了什么。我也没有通过谷歌找到任何东西。

2 个答案:

答案 0 :(得分: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_displaylist_filtersearch_fieldsorderingfilter_horizontalfieldsets和{{1 (add_fieldsets中提及django.contrib.auth.admin.UserAdmin的所有内容,我想我列出了所有内容)。

答案 1 :(得分:4)

您需要从sctratch创建表单,它不应该扩展UserCreationForm。 UserCreationForm在其中明确定义了用户名字段以及其他一些字段。你可以看一下here