Django 1.5: UserCreationForm & Custom Auth Model

前端 未结 2 1697
天命终不由人
天命终不由人 2020-12-05 20:46

I\'m using Django 1.5 & Python 3.2.3.

I\'ve got a custom Auth setup, which uses an email address instead of a username. There\'s no username def

相关标签:
2条回答
  • 2020-12-05 21:22

    Your UserCreationForm should look something like

    # 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
    

    You'll also want a user change form, which won't overrwrite the password field:

    class UserChangeForm(forms.ModelForm):
        password = ReadOnlyPasswordHashField()
    
        class Meta:
            model = CustomUser
    
        def clean_password(self):
            # always return the initial value
            return self.initial['password']
    

    Define these in your admin like this:

    #admin.py
    
    from .forms import UserChangeForm, UserAddForm
    
    class CustomUserAdmin(UserAdmin):
        add_form = UserCreationForm
        form = UserChangeForm
    

    You'll also need to override list_display, list_filter, search_fields, ordering, filter_horizontal, fieldsets, and add_fieldsets (everything in django.contrib.auth.admin.UserAdmin that mentions username, I think I listed all of it).

    0 讨论(0)
  • 2020-12-05 21:23

    You need to create your form from sctratch, it should not extend the UserCreationForm. The UserCreationForm have a username field explicitly defined in it as well as some other fields. You can look at it here.

    0 讨论(0)
提交回复
热议问题