Django 1.5:UserCreationForm & 自定义认证模型

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')

在文档中,自定义用户和内置表单指出它“必须为任何自定义用户模型重新编写”,我认为这就是我在这里要做的事情。然而,无论是它还是UserCreationForm文档都没有提到更多关于此的信息。因此,我不知道我错过了什么。我也没有通过谷歌找到任何有用的内容。
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_displaylist_filtersearch_fieldsorderingfilter_horizontalfieldsetsadd_fieldsets(在 django.contrib.auth.admin.UserAdmin 中提到 username 的所有内容,我认为我列出了所有内容)。


TwoScoops 在 save 方法中看起来很有趣 :) - Ellochka Cannibal
我在哪里可以找到这个TwoScoopsUserCreationForm? - DerShodan

4

您需要从头开始创建表单,而不应该扩展UserCreationForm。 UserCreationForm中已经明确定义了用户名字段以及其他一些字段。 您可以在此处查看它here


3
哎呀,虽然Django有很多好处,但这个问题真的很烦人。他们允许使用自定义auth而不需要用户名,但这会破坏UserCreationForm。感谢提示,至少我知道我没有做错事来导致我遇到的结果。 - Zamphatta
1
但是文档说这个表单应该被重写。而重写并不意味着从它继承,而是指一个新的表单。 - Aldarund

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接