Какова связь между «add_form» и «add_fieldsets» в Django UserAdmin? - PullRequest
0 голосов
/ 23 мая 2019

Я добавил пользовательскую модель в Django (версия 2.2), используя документацию на веб-сайте Django.

Пока мой код работает нормально, у меня возникают проблемы с пониманием корреляции между 'add_form' и 'add_fieldsets'.

В частности, в моем CustomUserCreationForm я включил только 3 поля - «мобильный» (это мое имя пользователя), «электронная почта» и «имя».

В мои add_fieldsets я включил дополнительные поля, которые я определил в моей модели - «account_name» и «пола».

Однако, хотя 'account_name' и 'пола' НЕ определены в моей add_form, все по-прежнему работает отлично! Может ли кто-нибудь помочь мне понять, почему?

Прочтите документацию по 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]
...