首页 文章

Django 1.5:UserCreationForm和Custom Auth Model

提问于
浏览
9

我正在使用Django 1.5和Python 3.2.3 .

我在模型中定义了've got a custom Auth setup, which uses an email address instead of a username. There' s no username . 这很好 . 然而,当我构建用户创建表单时,无论如何它都会添加用户名字段 . 所以我尝试确切地定义了我想要显示哪些字段,但它仍然在表单中强制使用用户名字段....即使它甚至不存在于自定义身份验证模型中 . 我怎么能让它停止这样做?

我的表格定义如下:

class UserCreateForm(UserCreationForm):

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

在文档中,Custom Users and Builtin Forms说它"Must be re-written for any custom user model."并且我认为's what I'm在这里做 . 既不是这个,也不是UserCreationForm documentation对此有更多的说法 . 所以我不会错过.1760167_m . 我也没有通过谷歌找到任何东西 .

2 回答

  • 13

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

  • 4

    你的_1760169应该是这样的

    # 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 (提及 usernamedjango.contrib.auth.admin.UserAdmin 中的所有内容,我想我列出了所有内容) .

相关问题