你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_display
, list_filter
, search_fields
, ordering
, filter_horizontal
, fieldsets
, and add_fieldsets
(django.contrib.auth.admin.UserAdmin
其中提到的所有内容username
,我想我都列出了所有内容)。