class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Password Confirmation', widget=forms.PasswordInput)
first_name = forms.CharField(label='First Name')
last_name = forms.CharField(label='Last Name')
class Meta:
model = User
fields = ['email', 'first_name', 'last_name']
def clean_password(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords do not match")
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
Here is my model:
class User(AbstractUser):
Our own User model. Made by overriding Django's own AbstractUser model.
We need to define this as the main user model in settings.py with
variable AUTH_USER_MODEL *IMPORTANT*
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(
max_length=255,
unique=True,
verbose_name="email address"
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
这里是admin.py
class UserAdmin(BaseUserAdmin):
add_form = UserCreationForm
list_display = ('email', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Permissions', {'fields': ('is_admin',)})
search_fields = ('email',)
ordering = ('email',)
admin.site.register(User, UserAdmin)
注意first_name和last_name。这两个字段并没有出现在表单中。我做错了什么,导致这些字段没有出现在用户创建表单中?我已经按照文档中的所有步骤操作了。
1 个回答
0 人赞同
找到了。你需要添加add_fieldsets,以实现这一目标。
add_fieldsets = (
(None, {