我找不到在管理员的“添加新用户页面”上显示自定义用户的自定义必填字段的方法。
我创建了一个扩展 AbstractUser 的自定义用户并添加了三个必需的自定义字段。我没有创建自定义 UserManager,因为我是从 AbstractUser 而不是 AbstractBaseUser 扩展的。
对于管理方面: 1. 我通过扩展创建了一个自定义 UserCreationForm。在元类中,我添加了这三个新的自定义字段
但我在管理员端看不到自定义字段。我做错了吗?
这是管理端的代码:
class MyUserCreationForm(UserCreationForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = get_user_model()
fields = ('customField1', 'customField2', 'customField3',)
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:
raise forms.ValidationError("Passwords don't match")
return password2
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["password1"])
if commit:
user.save()
return user
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
fieldsets = (
(None, {'fields': [('username', 'password', 'customField1', 'customField2', 'customField3'),]}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
admin.site.register( CustomUser, MyUserAdmin)