Problem with register the User in admin

I tried to register the user, and I want to configure the admin site to have a permission field, groups field, etc. (Like in the picture)
but I have these errors like result:
Errors:

ERRORS:
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E012) There are duplicate field(s) in ‘fieldsets[1][1]’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E012) There are duplicate field(s) in ‘fieldsets[2][1]’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E012) There are duplicate field(s) in ‘fieldsets[3][1]’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E033) The value of ‘ordering[0]’ refers to ‘username’, which is not a field of ‘accounts.AppBaseUser’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E108) The value of ‘list_display[0]’ refers to ‘username’, which is not a callable, an attribute of ‘AppBaserUser’, or an attribute or method on ‘accounts.AppBaseUser’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E108) The value of ‘list_display[2]’ refers to ‘first_name’, which is not a callable, an attribute of ‘AppBaserUser’, or an attribute or method on ‘accounts.AppBaseUser’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E108) The value of ‘list_display[3]’ refers to ‘last_name’, which is not a callable, an attribute of ‘AppBaserUser’, or an attribute or method on ‘accounts.AppBaseUser’.
<class ‘beauty_salon_manage_sistem.accounts.admin.AppBaserUser’>: (admin.E116) The value of ‘list_filter[2]’ refers to ‘is_active’, which does not refer to a Field.

System check identified 8 issues (0 silenced).

This is my code:

`#admin:
 
@admin.register(AppBaseUser)
class AppBaserUser(UserAdmin):
    add_form = RegistrationAppUserForm
    # form = AppUserEditForm
    fieldsets = (
        (
            None,
            {
                'fields': (
                    'email',
                    'password',
                ),
            }),
        (
            'Personal info',
            {
                'fields': (
                    'first_name',
                    'last_name',
                    'email',
 
                ),
            },
        ),
        (
            'Permissions',
            {
                'fields': (
                    'is_active',
                    'is_staff',
                    'is_superuser',
                    'groups',
                    'user_permissions',
                ),
            },
        ),
        (
            'Important dates',
            {
                'fields': (
                    'last_login',
                    'date_joined',
                ),
            },
        ),
    )
 
    def get_form(self, request, obj=None, **kwargs):
        return super().get_form(request, obj, **kwargs)
 
 
#models:
 
class AppBaseUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        unique=True,
        null=False,
        blank=False,
    )
 
    is_staff = models.BooleanField(
        default=True,
    )
 
    USERNAME_FIELD = 'email'
 
    objects = AppBaseUserManager()
 
    @property
    def get_full_name_with_profile(self):
        profile_full_name = AppStaffProfile.objects.get(pk=self.pk).get_full_name
        if profile_full_name:
            return f'{profile_full_name}'
        return f'{self.email}'
 
    def __str__(self):
        if self.get_full_name_with_profile:
            return self.get_full_name_with_profile
        f'{self.email}'
 
    class Meta:
        verbose_name = 'User'
 
 
class AppStaffProfile(models.Model):
    user = models.OneToOneField(AppBaseUser, primary_key=True, on_delete=CASCADE, )
 
    MIN_LEN_FIRST_NAME = 2
    MAX_LEN_FIRST_NAME = 40
 
    MIN_LEN_LAST_NAME = 2
    MAX_LEN_LAST_NAME = 40
 
    MAX_LEN_POSITION = 100
 
    first_name = models.CharField(
        max_length=MAX_LEN_FIRST_NAME,
        null=True,
        blank=True,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ]
    )
 
    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=True,
        blank=True,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ]
    )
 
    position = models.CharField(
        max_length=MAX_LEN_POSITION,
        null=True,
        blank=True,
    )
 
    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'
 
    def __str__(self):
        if self.get_full_name:
            return f'{self.get_full_name} - {self.position}'
        return self.user.email
 
    class Meta:
        verbose_name = 'Staff'
 
 
#forms:
 
class RegistrationAppUserForm(UserCreationForm):
    MIN_LEN_FIRST_NAME = 2
    MAX_LEN_FIRST_NAME = 40
 
    MIN_LEN_LAST_NAME = 2
    MAX_LEN_LAST_NAME = 40
 
    MAX_LEN_POSITION = 100
 
    first_name = forms.CharField(
        max_length=MAX_LEN_FIRST_NAME,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ],
        widget=forms.TextInput(attrs={'placeholder': 'First name'}),
        required=True,
    )
 
    last_name = forms.CharField(
        max_length=MAX_LEN_LAST_NAME,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ],
        widget=forms.TextInput(attrs={'placeholder': 'Last name'}),
        required=True,
    )
 
    position = forms.CharField(
        max_length=MAX_LEN_POSITION,
        widget=forms.TextInput(attrs={'placeholder': 'Position'}),
        required=True,
    )
 
    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'placeholder': 'Password',
            'label': 'Password'
        }),
    )
    password2 = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'placeholder': 'Repeat password',
        })
    )
 
    class Meta:
        model = UserModel
        fields = ('email',)
        widgets = {
            'email': forms.TextInput(attrs={
                'placeholder': 'Enter your email',
            }),
 
        }
    def cleaned_data_fist_name(self):
        return self.cleaned_data['first_name']
 
    def cleaned_data_last_name(self):
        return self.cleaned_data['last_name']
 
    def cleaned_data_position(self):
        return self.cleaned_data['position']
 
    def save(self, commit=True):
        user = super().save(commit=commit)
        profile = AppStaffProfile(
            first_name=self.cleaned_data['first_name'],
            last_name=self.cleaned_data['last_name'],
            position=self.cleaned_data['position'],
            user=user,
        )
        if commit:
            profile.save()
 
        return user
 
 
 
class AppProfileEditForm(UserChangeForm):
    class Meta:
        model = AppStaffProfile
        fields = "__all__"
 
 
class AppUserEditForm(UserChangeForm):
    class Meta:
        model = UserModel
        fields = ('email',)`

Can you help me, where is my mistake?

I can see a couple things so far:

  • You have your email field in both the None and Personal info fieldsets.

  • You are defining AppBaserUser as a class inheriting from UserAdmin, this means that everything defined in UserAdmin is going to apply to AppBaserUser unless you override it. That means that the parent class definitions for add_fieldsets, list_display, search_field, and ordering would also apply - causing a problem because you don’t have fields named username, first_name or last_name in your user model.

I would suggest that you don’t inherit from UserAdmin, inherit from BaseUserAdmin. (See the full example)

Some other side notes and recommendations -

You don’t need to write this as a query. Since AppStaffProfile has a one-to-one relationship with AppBaseUser, the related profile to a user (self in this case), you can access the get_full_name property directly as self.appstaffprofile.get_full_name. (You have access to the profile directly from any instance of AppBaseUser through the appstaffprofile related name.)

This is an extraneous condition in this function. Since get_full_name_with_profile will already return self.email if there is no profile_full_name, the if statement in this function will never be False.

I’m not seeing where these are being used or why they might be defined. You might want to remove them to remove unnecessary “code clutter”.

Ok, but our teacher showed us like this and I am really confused.
I do it like this and again when I click on some of the users in admin I have this error:

When I want to add

FieldError at /admin/accounts/appbaseuser/add/

Unknown field(s) (firs_name, last_name, is_active, position, date_joined) specified for AppBaseUser. Check fields/fieldsets/exclude attributes of class AppBaseUserAdmin

And when I click in the existing one:

this is how I do it now, I really can’t understand how to give permission in this situation. I don’t want to change users from the scratch. My code now:


@admin.register(UserModel)
class AppBaseUserAdmin(admin.ModelAdmin):
    add_form= RegistrationAppUserForm

    fieldsets = (
        (
        (
            'Permissions',
            {
                'fields': (
                    'is_active',
                    'is_staff',
                    'is_superuser',
                    'groups',
                    'user_permissions',
                ),
            },
        ),
        (
            'Personal info',
            {
                'fields': (
                    'firs_name',
                    'last_name',
                    'position',

                ),
            },
        ),
        (
            'Important dates',
            {
                'fields': (
                    'last_login',
                    'date_joined',
                ),
            },
        ),
    ))

You are now inheriting from ModelAdmin, which means you need to specify all the attributes needed by an admin class, such as fields.

Review the docs at The Django admin site | Django documentation | Django to see what you need to do and all the options available to define a ModelAdmin class.

Yes, I saw this, but I don’t know how to overwrite the Permission.
I will try everything :slight_smile:

На ср, 7.12.2022 г., 17:41 ч. Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> написа:

The errors you are seeing here have nothing to with permissions. You should get your basic admin class working first.

It is not give me to inherit BaseUserAdmin…

На ср, 7.12.2022 г., 17:41 ч. Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> написа:

Ok, that doesn’t match the snippet you posted at Problem with register the User in admin - #3 by reniboyanova earlier.

So what is the specific issue for which you are requesting assistance here? I’m starting to get lost with the different versions of things you are posting, so I’d suggest you copy/pasting the exact code for which you currently have questions, along with the current error messages that you’re needing help with.

(Also, please do not post screen images of code. Always copy/paste the code itself into your posts.)