Django 1.5:UserCreationForm和Custom Auth Model

Zam*_*tta 9 django django-models django-forms python-3.x

我正在使用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')
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*lor 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
Run Code Online (Sandbox Code Playgroud)

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

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

    class Meta:
        model = CustomUser

    def clean_password(self):
        # always return the initial value
        return self.initial['password']
Run Code Online (Sandbox Code Playgroud)

在您的管理员中定义这些:

#admin.py

from .forms import UserChangeForm, UserAddForm

class CustomUserAdmin(UserAdmin):
    add_form = UserCreationForm
    form = UserChangeForm
Run Code Online (Sandbox Code Playgroud)

您还需要重写list_display,list_filter,search_fields,ordering,filter_horizontal,fieldsets,和add_fieldsets(一切都在django.contrib.auth.admin.UserAdmin那提到username,我想我列出的所有的话).


Ald*_*und 4

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

  • 呃,尽管 Django 有很多优点,但这是一个疯狂的缺点。它们允许在没有用户名的情况下进行自定义身份验证,但这会破坏 UserCreationForm。谢谢。至少我知道我没有做错什么来得到我得到的结果。 (3认同)