如何在CustomUserCreationForm中添加字段?

时间:2019-10-27 15:42:15

标签: django django-models django-forms django-admin django-users

Forms.py

class CustomUserCreationForm(UserCreationForm):

    #phone_number = forms.CharField(max_length = 100)
    class Meta:
        model = CustomUser
        fields = ('username', 'email','first_name','last_name', 'phone_number', 'middle_name')

Admin.py

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    fieldsets = (
        (('User'), {'fields': ('username', 'email', 'phone_number', 'first_name', 'last_name', 'middle_name',
         'is_staff', 'is_superuser', 'is_active', 'is_parent', 'is_teacher')}),
    )

Models.py Admin.py 中的所有字段均在此处声明,没有错误

class CustomUser(AbstractUser):
    phone_number = models.CharField(max_length = 100, blank=True, null = True)
    first_name = models.CharField(max_length = 100, default = '')
    last_name = models.CharField(max_length = 100, default = '')

AddNewUser Image Here

如您所见,我尝试直接在CustomUserCreationForm中添加一个Charfield,也尝试添加字段,但是只要我添加新用户,它就不会出现。

1 个答案:

答案 0 :(得分:0)

这应该对您有用

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    fieldsets = (
        (('None'), {'fields': ('username', 'email', 'phone_number', 'first_name', 'last_name', 'middle_name',
         'is_staff', 'is_superuser', 'is_active', 'is_parent', 'is_teacher')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'phone_number', 'first_name', 'last_name', 'middle_name',
         'is_staff', 'is_superuser', 'is_active', 'is_parent', 'is_teacher' ),
        }),
    )
    admin.site.register(CustomUser, CustomUserAdmin),