[英]Custom fields not coming during user creation in Django
I have created a custom user creation form:我创建了一个自定义用户创建表单:
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
Here is the admin.py这是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)
Note the first_name and last_name.注意 first_name 和 last_name。 These two fields aren't coming in the form.
这两个字段没有出现在表单中。 What am I doing wrong due to which these fields aren't coming in the user creation form?
由于这些字段没有出现在用户创建表单中,我做错了什么? I've followed all the steps from the documentation.
我已经按照文档中的所有步骤进行操作。
Found it.找到了。 You need to add add_fieldsets in order to achieve this.
您需要添加 add_fieldsets 才能实现此目的。
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'password1', 'password2'),
}),
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.