Django UserAdmin中“ add_form”和“ add_fieldsets”之间是什么关系?

时间:2019-05-23 12:44:59

标签: django django-admin

我已使用Django网站上的文档向Django(版本2.2)添加了自定义用户模型。

虽然我的代码运行正常,但我无法理解'add_form'和'add_fieldsets'之间的相关性。

具体地说,在我的CustomUserCreationForm中,我仅包括3个字段-“移动”(这是我的用户名),“电子邮件”和“名称”。

在我的add_fieldsets中,包括了我在模型中定义的其他字段-'account_name'和'gender'。

但是,尽管我的add_form中未定义'account_name'和'gender',但一切仍然正常!有人可以帮我理解为什么吗?

阅读https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

上的文档

我的模特:

class CustomUser(AbstractBaseUser, PermissionsMixin, GuardianUserMixin):
    """
    Customer user model which uses the user mobile number as the username.
    """
    mobile = models.CharField(
        max_length=15,
        unique=True,
        verbose_name='user mobile number',
        help_text='mobile number with country code (without the +)',
    )
    email = models.EmailField(max_length=50, blank=False)
    name = models.CharField('full name', max_length=50, blank=False)
    account_name = models.CharField('company', max_length=80, blank=False)
    gender = models.CharField('gender', max_length=6, blank=False)

    is_active = models.BooleanField('active', default=False)
    is_staff = models.BooleanField('staff status', default=False)

    date_joined = models.DateTimeField('date joined', default=timezone.now)

    objects = CustomUserManager()

    USERNAME_FIELD = 'mobile'
    EMAIL_FIELD = 'email'

    # Required fields only for the createsuperuser management command.
    REQUIRED_FIELDS = ['email', 'name', 'account_name', 'gender']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name    

    def __unicode__(self):
        return self.mobile
class CustomUserCreationForm(forms.ModelForm):
    """ 
    A form for creating new users. Includes all the required fields
    plus a repeated password

    Used only by the admin module.
    """

    password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput)

    class Meta:
        model = CustomUser
        fields = ('mobile', 'email', 'name',)

    def clean_password2(self):
        # check the two passwords 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(CustomUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        user.is_active = True
        if commit:
            user.save()
        return user

我的UserAdmin

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances.
    form = CustomUserChangeForm
    add_form = CustomUserCreationForm

    # The fields to be used in displaying the User model.
    # These override the def on the BaseUserAdmin
    list_display = ('mobile', 'email', 'name', 'is_superuser', 'is_staff', 'is_active',)
    list_filter = ('is_superuser', 'is_staff', 'groups',)

    fieldsets = (
        (None, {'fields' : ('mobile', 'password')}),
        ('Other info', {'fields': ('email', 'name', 'account_name', 'date_joined',)}),
        ('Permissions', {'fields' : ('is_superuser', 'is_active', 'is_staff', 'groups', 'user_permissions')}),
    )

    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields' : ('mobile', 'email', 'name', 'account_name', 'gender',
                        'password1', 'password2',),
        },),
    )

    search_fields = ('mobile', 'name', 'email', 'account_name')
    ordering = ('mobile',)
    filter_horizontal = ('groups', 'user_permissions',)
    inlines = [AssetUsersInline, ServiceUsersInline]

0 个答案:

没有答案