I have 'DoesNotExist' exception in Admin site

Hello guys,
I am doing my first project in Django and I really need some help - I get this exception in the admin site

DoesNotExist at /admin/accounts/appcustomeruser/3/change/

AppStaffProfile matching query does not exist.

and this is in Pycharm console:

beauty_salon_manage_sistem.accounts.models.AppStaffProfile.DoesNotExist: AppStaffProfile matching query does not exist.
[22/Nov/2022 17:14:06] “GET /admin/accounts/appcustomeruser/3/change/ HTTP/1.1” 500 623959

in models.py:

class AppCustomerUser(models.Model):
    MIN_LEN_FIRST_NAME = 2
    MAX_LEN_FIRST_NAME = 40

    MIN_LEN_LAST_NAME = 2
    MAX_LEN_LAST_NAME = 40

    MAX_LEN_PHONE_NUMBER = len('+359888888888')
    MIN_LEN_PHONE_NUMBER = len('+359888888888')
    #
    # TODO Make it with enumerate!
    GENDER_CHOICES = [('Male', 'Male'), ('Female', 'Female'), ('Do not show', 'Do not show'), ]
    MAX_LEN_GENDER = len('Do not show')
    #
    HAIR_TYPES_CHOICES = [
        ('Straight hair', 'Straight hair'),
        ('Wavy hair', 'Wavy hair'),
        ('Curly hair', 'Curly hair'),
        ('Kinky hair', 'Kinky hair'),
        ('I am not sure', 'I am not sure'),
    ]

    MAX_LEN_HAIR_TYPES = len('I am not sure')

    HAIR_LONG_CHOICES = [
        ('Short hair', 'Short hair'),
        ('Middle hair', 'Middle hair'),
        ('Long hair', 'Long hair'),
        ('Very long hair', 'Very long hair'),
        ('I am not sure', 'I am not sure'),
    ]
    MAX_LEN_HAIR_LONG = len('Very long hair')

    MAX_LEN_FURTHER_EXPLANATION = 250

    hair_stylist = models.ManyToManyField(AppBaseUser)

    first_name = models.CharField(
        max_length=MAX_LEN_FIRST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ],
    )

    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ]
    )

    date_of_join = models.DateField(
        auto_now_add=True,
        blank=True,
    )

    phone_number = models.CharField(
        max_length=MAX_LEN_PHONE_NUMBER,
        validators=[validators.MinLengthValidator(MIN_LEN_PHONE_NUMBER), ],
        null=False,
        blank=False,
    )

    gender = models.CharField(
        max_length=MAX_LEN_GENDER,
        choices=GENDER_CHOICES,
    )

    hair_type = models.CharField(
        max_length=MAX_LEN_HAIR_TYPES,
        choices=HAIR_TYPES_CHOICES,
    )

    hair_long = models.CharField(
        max_length=MAX_LEN_HAIR_LONG,
        choices=HAIR_LONG_CHOICES,
    )

    further_explanation = models.TextField(
        max_length=MAX_LEN_FURTHER_EXPLANATION,
        null=True,
        blank=True,
    )

    is_staff = models.BooleanField(default=False,)
    is_superuser = models.BooleanField(default=False,)

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    @property
    def full_name_and_phone_number(self):
        return f'{self.get_full_name} - {self.phone_number}'

    def __str__(self):
        return f'{self.get_full_name} - {self.pk}'

    class Meta:
        verbose_name = 'Customer'

in views.py:

class CreateCustomer(CreateView):
    template_name = 'accounts/adding_customer.html'
    form_class = AddingCustomerForm
    success_url = reverse_lazy('add customer')

in admin.py:

@admin.register(AppStaffProfile)
class AppStaffProfileAdmin(admin.ModelAdmin):
    pass

I have correct records in my DB, but when I click on one of them in localhost:8000/admin it crashes

I see a reference to AppBaseUser in a ManyToManyField, but I don’t see any direct references to a model named AppStaffProfile. Where and how is AppStaffProfile related to AppCustomerUser?

Can you post the definitions for both AppBaseUser and AppStaffProfile?

Can you also provide some additional descriptive information about your models that might help identify what’s going on?

Thank you for this answer!

Yes - my idea is e Beauty Salon Management System, so every one of the customers can have more than one “stylist” - A hairstylist, Makeup artist, etc., and every beauty staff have more than one repeatable customer.

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
        return f'{profile_full_name}'

    def __str__(self):
        return self.get_full_name_with_profile


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=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ]
    )

    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ]
    )

    position = models.CharField(
        max_length=MAX_LEN_POSITION,
        null=False,
        blank=False,
    )

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    def __str__(self):
        return f'{self.get_full_name} - {self.position}'

    class Meta:
        verbose_name = 'Staff'

Side note - in your class definitions, Mixin classes must appear before the base class for the model or view being inherited.
I’m not sure just how critical it is for this specific issue, but it does need to be fixed.

So the root issue is that you apparently do not have an AppStaffProfile for one or more of your AppBaseUser models. The problem is that in your AppBaseUser model, your get_full_name_with_profile property is trying to get the related instance of AppStaffProfile - but if there is no AppStaffProfile for that AppBaseUser, this error will be thrown.

You’ll need to either ensure that there is an instance of AppStaffProfile for every AppBaseUser, or change this method to catch (or prevent) the exception when there is no AppStaffProfile and return some suitable alternative.

I am really a beginner in Django, so is a lot confusing to understand some of Django’s Principes:

this is my 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',
        }),
    )
    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',
            }),

        }
        labels = {
            'email': '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 AddingCustomerForm(forms.ModelForm):
    class Meta:
        model = AppCustomerUser
        exclude = ('date_of_join', 'is_staff', 'is_superuser',)
        widgets = {
            'first_name': forms.TextInput(attrs={
                'placeholder': 'First Name:', 'label': 'Enter your first name:', 'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={
                'placeholder': 'Last Name:','class': 'form-control'}),
            'phone_number': forms.TextInput(attrs={
                'placeholder': 'Phone number:','class': 'form-control'}),
            'further_explanation': forms.Textarea(attrs={
                'placeholder': 'Additional information:','class': 'form-control'}),

        }

and my views (they are just to see if my code is working):

class ShowAppUsers(ListView):
    model = UserModel
    template_name = 'accounts/show_app_users.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['staffs'] = UserModel.objects.all()
        context['customers'] = AppCustomerUser.objects.all()
        return context


class CreateAppStaffUser(CreateView):
    template_name = 'accounts/staff_creation_form.html'
    form_class = RegistrationAppUserForm
    success_url = reverse_lazy('index page')

    def form_valid(self, form):
        result = super().form_valid(form)
        # user => self.object
        # request => self.request
        login(self.request, self.object)
        return result


class CreateCustomer(CreateView):
    template_name = 'accounts/adding_customer.html'
    form_class = AddingCustomerForm
    success_url = reverse_lazy('add customer')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['hairstylists'] = [person.get_full_name for person in AppStaffProfile.objects.all()]
        return context

This required=True arguments I write it now

What is this UserModel that you are referencing here:

and here:

I dont understand what you mean

You have the line: model = UserModel in two places. What is UserModel?

This is AppBaseUser, I get it with:
UserModel = get_user_model()
And set AppBaseUser in settings.py

На вт, 22.11.2022 г., 21:25 ч. Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> написа:

Ok, so what I would suggest is that you find out if there is an instance of AppBaseUser without a related instance of AppStaffProfile.

You can do this directly in your database using the query tool of your choice, or you can change your get_full_name_with_profile method to not throw an error in the situation where there is no AppStaffProfile for any instance of AppBaseUser.

For example, you could temporarily change it to:

def get_full_name_with_profile(self):
  return self.email

Yes, it’s not “right”, but it should get you past the error you’re reporting to where you can go into the admin and fix it there.

Thank’s a lot! I will try this.

На вт, 22.11.2022 г., 22:19 ч. Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> написа:

Could I ask you for help again, please?

I want to show only AppStaffProfile customers,
so It means that my AppBaseUser is in a OneToOne relation in AppStaffProfile (it’s to handle the names and position and to collect only important information about users - email for registration and password).
But my AppCustomer is ManytoManyField - and till now I fixed all the problems, but in my template, I want to show only the current Users customers.
P.S. - these templates are just to show me if the code works correct.

The views.py:

class ShowAppUsers(ListView):
    model = UserModel
    template_name = 'accounts/show_app_customrs.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['staffs'] = UserModel.objects.all()
        context['customers'] = AppCustomerUser.objects.all()
        context['my_customers'] = AppStaffProfile.objects.filter(appcustomeruser__hair_stylist__user_id=self.request.user.pk)
        return context

the template:

{% extends 'common/index_page.html' %}
{% block content %}
    {% for customer in customers %}
        {% if my_customers %}
            <li>{{ customer.full_name_and_phone_number }}</li>
            <p>Customer's procedures <a href="{% url 'details of user' %}" class="btn btn-outline-info" role="button">Show
                info</a></p>
{% endif %}
    {% endfor %}
            <ul>You don't have any customers yet!</ul>

    <ul>
        All beauty salon customers are: {{ customers.count }}!
    </ul>
    {% if staffs %}
        <ul>
            We have {{ staffs.count }} staffs!
        </ul>
    {% else %}
        <ul>Dont have any staff yet!</ul>
    {% endif %}
{% endblock %}


my models.py:

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 self.email

    def __str__(self):
        return self.get_full_name_with_profile


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=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ]
    )

    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ]
    )

    position = models.CharField(
        max_length=MAX_LEN_POSITION,
        null=False,
        blank=False,
    )

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    def __str__(self):
        return f'{self.get_full_name} - {self.position}'

    class Meta:
        verbose_name = 'Staff'


class AppCustomerUser(models.Model):
    MIN_LEN_FIRST_NAME = 2
    MAX_LEN_FIRST_NAME = 40

    MIN_LEN_LAST_NAME = 2
    MAX_LEN_LAST_NAME = 40

    MAX_LEN_PHONE_NUMBER = len('+359888888888')
    MIN_LEN_PHONE_NUMBER = len('+359888888888')
    #
    # TODO Make it with enumerate!
    GENDER_CHOICES = [('Male', 'Male'), ('Female', 'Female'), ('Do not show', 'Do not show'), ]
    MAX_LEN_GENDER = len('Do not show')
    #
    HAIR_TYPES_CHOICES = [
        ('Straight hair', 'Straight hair'),
        ('Wavy hair', 'Wavy hair'),
        ('Curly hair', 'Curly hair'),
        ('Kinky hair', 'Kinky hair'),
        ('I am not sure', 'I am not sure'),
    ]

    MAX_LEN_HAIR_TYPES = len('I am not sure')

    HAIR_LONG_CHOICES = [
        ('Short hair', 'Short hair'),
        ('Middle hair', 'Middle hair'),
        ('Long hair', 'Long hair'),
        ('Very long hair', 'Very long hair'),
        ('I am not sure', 'I am not sure'),
    ]
    MAX_LEN_HAIR_LONG = len('Very long hair')

    MAX_LEN_FURTHER_EXPLANATION = 250

    hair_stylist = models.ManyToManyField(AppStaffProfile, verbose_name='Hair stylist:')


    first_name = models.CharField(
        max_length=MAX_LEN_FIRST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ],
        verbose_name='First name:',
    )

    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ],
        verbose_name='Last name:',
    )

    date_of_join = models.DateField(
        auto_now_add=True,
        blank=True,
    )

    phone_number = models.CharField(
        max_length=MAX_LEN_PHONE_NUMBER,
        validators=[validators.MinLengthValidator(MIN_LEN_PHONE_NUMBER), ],
        null=False,
        blank=False,
        verbose_name='Phone number:',
    )

    gender = models.CharField(
        max_length=MAX_LEN_GENDER,
        choices=GENDER_CHOICES,
        verbose_name='Gender:',
    )

    hair_type = models.CharField(
        max_length=MAX_LEN_HAIR_TYPES,
        choices=HAIR_TYPES_CHOICES,
        verbose_name='Hair type:',
    )

    hair_long = models.CharField(
        max_length=MAX_LEN_HAIR_LONG,
        choices=HAIR_LONG_CHOICES,
        verbose_name='Hair long:',
    )

    further_explanation = models.TextField(
        max_length=MAX_LEN_FURTHER_EXPLANATION,
        null=True,
        blank=True,
        verbose_name='Additional information:',
    )

    is_staff = models.BooleanField(default=False, )
    is_superuser = models.BooleanField(default=False, )

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    @property
    def full_name_and_phone_number(self):
        return f'{self.get_full_name} - {self.phone_number}'

    def __str__(self):
        return f'{self.get_full_name}'

    class Meta:
        verbose_name = 'Customer'

Could I ask you for help again, please?

I want to show only AppStaffProfile customers,
so It means that my AppBaseUser is in a OneToOne relation in AppStaffProfile (it’s to handle the names and position and to collect only important information about users - email for registration and password).
But my AppCustomer is ManytoManyField - and till now I fixed all the problems, but in my template, I want to show only the current Users customers.
P.S. - these templates are just to show me if the code works correct.

The views.py:

class ShowAppUsers(ListView):
    model = UserModel
    template_name = 'accounts/show_app_customrs.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['staffs'] = UserModel.objects.all()
        context['customers'] = AppCustomerUser.objects.all()
        context['my_customers'] = AppStaffProfile.objects.filter(appcustomeruser__hair_stylist__user_id=self.request.user.pk)
        return context`Preformatted text`

the template

{% extends 'common/index_page.html' %}
{% block content %}
    {% for customer in customers %}
        {% if my_customers %}
            <li>{{ customer.full_name_and_phone_number }}</li>
            <p>Customer's procedures <a href="{% url 'details of user' %}" class="btn btn-outline-info" role="button">Show
                info</a></p>
{% endif %}
    {% endfor %}
            <ul>You don't have any customers yet!</ul>

    <ul>
        All beauty salon customers are: {{ customers.count }}!
    </ul>
    {% if staffs %}
        <ul>
            We have {{ staffs.count }} staffs!
        </ul>
    {% else %}
        <ul>Dont have any staff yet!</ul>
    {% endif %}
{% endblock %}

my models.py:

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 self.email

    def __str__(self):
        return self.get_full_name_with_profile


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=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ]
    )

    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ]
    )

    position = models.CharField(
        max_length=MAX_LEN_POSITION,
        null=False,
        blank=False,
    )

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    def __str__(self):
        return f'{self.get_full_name} - {self.position}'

    class Meta:
        verbose_name = 'Staff'


class AppCustomerUser(models.Model):
    MIN_LEN_FIRST_NAME = 2
    MAX_LEN_FIRST_NAME = 40

    MIN_LEN_LAST_NAME = 2
    MAX_LEN_LAST_NAME = 40

    MAX_LEN_PHONE_NUMBER = len('+359888888888')
    MIN_LEN_PHONE_NUMBER = len('+359888888888')
    #
    # TODO Make it with enumerate!
    GENDER_CHOICES = [('Male', 'Male'), ('Female', 'Female'), ('Do not show', 'Do not show'), ]
    MAX_LEN_GENDER = len('Do not show')
    #
    HAIR_TYPES_CHOICES = [
        ('Straight hair', 'Straight hair'),
        ('Wavy hair', 'Wavy hair'),
        ('Curly hair', 'Curly hair'),
        ('Kinky hair', 'Kinky hair'),
        ('I am not sure', 'I am not sure'),
    ]

    MAX_LEN_HAIR_TYPES = len('I am not sure')

    HAIR_LONG_CHOICES = [
        ('Short hair', 'Short hair'),
        ('Middle hair', 'Middle hair'),
        ('Long hair', 'Long hair'),
        ('Very long hair', 'Very long hair'),
        ('I am not sure', 'I am not sure'),
    ]
    MAX_LEN_HAIR_LONG = len('Very long hair')

    MAX_LEN_FURTHER_EXPLANATION = 250

    hair_stylist = models.ManyToManyField(AppStaffProfile, verbose_name='Hair stylist:')


    first_name = models.CharField(
        max_length=MAX_LEN_FIRST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_FIRST_NAME),
            validate_only_letters,
        ],
        verbose_name='First name:',
    )

    last_name = models.CharField(
        max_length=MAX_LEN_LAST_NAME,
        null=False,
        blank=False,
        validators=[
            validators.MinLengthValidator(MIN_LEN_LAST_NAME),
            validate_only_letters,
        ],
        verbose_name='Last name:',
    )

    date_of_join = models.DateField(
        auto_now_add=True,
        blank=True,
    )

    phone_number = models.CharField(
        max_length=MAX_LEN_PHONE_NUMBER,
        validators=[validators.MinLengthValidator(MIN_LEN_PHONE_NUMBER), ],
        null=False,
        blank=False,
        verbose_name='Phone number:',
    )

    gender = models.CharField(
        max_length=MAX_LEN_GENDER,
        choices=GENDER_CHOICES,
        verbose_name='Gender:',
    )

    hair_type = models.CharField(
        max_length=MAX_LEN_HAIR_TYPES,
        choices=HAIR_TYPES_CHOICES,
        verbose_name='Hair type:',
    )

    hair_long = models.CharField(
        max_length=MAX_LEN_HAIR_LONG,
        choices=HAIR_LONG_CHOICES,
        verbose_name='Hair long:',
    )

    further_explanation = models.TextField(
        max_length=MAX_LEN_FURTHER_EXPLANATION,
        null=True,
        blank=True,
        verbose_name='Additional information:',
    )

    is_staff = models.BooleanField(default=False, )
    is_superuser = models.BooleanField(default=False, )

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    @property
    def full_name_and_phone_number(self):
        return f'{self.get_full_name} - {self.phone_number}'

    def __str__(self):
        return f'{self.get_full_name}'

    class Meta:
        verbose_name = 'Customer'

I’m not sure I understand what you’re looking for here.

If I understand it correctly you’re assuming that the current User also has an AppStaffProfile, which then has a many-to-many relationship with AppCustomerUser. What you’re looking for is the set of AppCustomerUser related to that current user.

If that’s correct, then the set of AppCustomerUser related to request.user would be AppCustomerUser.objects.filter(hair_stylist__user=request.user)

You understand me correctly, this is ny student projects so maybe it’s a bit confusing in code, but I will try your advice.

На пт, 25.11.2022 г., 04:11 ч. Ken Whitesell via Django Forum <notifications@djangoproject.discoursemail.com> написа:

This is not the solution, it returns the same like:

 context['customers'] = AppCustomerUser.objects.all()
 context['my_customers'] = AppCustomerUser.objects.filter(hair_stylist__user=self.request.user)

I want to take this relationship, but my login is not with a profile, but whit a user

I don’t understand what I’m looking at here. I see two pictures of “something”, but nothing to tell me what that “something” is.

If you run this query in your Django shell, what do you get as the results of the queryset?

Also, you’re putting the results of your query in context['my_customers'], but you’re not iterating over that queryset in your template. You’re iterating over customers which is the unfiltered query on AppCustomerUser.

I fixed this, thank you! But I still have some problems that I cant understand.
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?