相关文章推荐
奔跑的猴子  ·  android多个library ...·  3 月前    · 
卖萌的黄豆  ·  Oops!!! - 简书·  1 年前    · 
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。这两个字段并没有出现在表单中。我做错了什么,导致这些字段没有出现在用户创建表单中?我已经按照文档中的所有步骤操作了。

4 个评论
如果我没有看错的话,你可能需要覆盖UserAdmin.add_fieldsets
在你的项目设置中,你必须提到你的授权用户模型
@lain 让我看看。
@bmons已经完成。我得到了这个表格。我的问题是不同的。
python
django
django-models
django-3.0
Mithil Bhoras
Mithil Bhoras
发布于 2020-01-05
1 个回答
Mithil Bhoras
Mithil Bhoras
发布于 2020-01-05
已采纳
0 人赞同

找到了。你需要添加add_fieldsets,以实现这一目标。

add_fieldsets = (
        (None, {