您可以将表单代码添加到 admin.py 文件中。但是,您还需要添加表单类的定义,而不仅仅是 save() 方法和 UserAdmin 子类的定义。我认为示例将阐明:
class UserCreationForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ('email',)
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
class CustomUserAdmin(UserAdmin):
# The forms to add and change user instances
add_form = UserCreationForm
list_display = ("email",)
ordering = ("email",)
fieldsets = (
(None, {'fields': ('email', 'password', 'first_name', 'last_name')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active')}
),
)
filter_horizontal = ()
admin.site.register(CustomUser, CustomUserAdmin)
这应该让你开始。您将需要自定义类的字段以匹配您的用户类的字段。
更多信息在这里:https ://docs.djangoproject.com/en/dev/topics/auth/customizing/