V
V
vagitaku2019-05-23 17:00:18
Django
vagitaku, 2019-05-23 17:00:18

How to access another model (OneToOne) from proxy model in forms.ModelForm?

There is an AdvancedUser(models.Model) model:

class AdvancedUser(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        verbose_name='Пользователь')
    phone_number = models.CharField(
        max_length=10,
        blank=True,
        verbose_name='Номер телефона')
    patronymic = models.CharField(
        max_length=60,
        blank=True,
        verbose_name='Отчетсво')

    def __str__(self):
        return ' '.join([self.user.last_name, self.user.first_name, self.patronymic])

    class Meta:
        verbose_name = 'Данные клиента'
        verbose_name_plural = 'Данные клиентов'
class Driver(AdvancedUser):
    class Meta:
        proxy = True
        verbose_name = 'Данные водителя'
        verbose_name_plural = 'Данные водиетелей'

It is connected OneToOne to the default auth_user. There is also a proxy model that inherits the AdvancedUser
Driver (proxy model) is registered in the admin panel like this:
class UserAdvancedDriverAdmin(admin.ModelAdmin):

    def get_queryset(self, request):
        group = Group.objects.get(name='Водитель')
        queryset = super().get_queryset(request).filter(user__is_staff=True, user__groups__name=group.name)
        return queryset

    list_display = ['get_last_name', 'get_first_name', 'patronymic' ]

    def get_first_name(self, obj):
        return obj.user.first_name

    def get_last_name(self, obj):
        return obj.user.last_name

    def has_add_permission(self, obj=None):
        return False

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        driver = form.base_fields["user"]

        driver.widget.can_add_related = False
        driver.widget.can_change_related = False

        return form

    get_first_name.short_description = 'Имя'
    get_last_name.short_description = 'Фамилия'
    form = DriverAdminForm

    class Meta:
        model = Driver

It is necessary that through the admin panel it was possible to edit the AdvancdeUser and auth_user data.
This is how I'm trying to do it (forms.py):
class DriverAdminForm(forms.ModelForm):
  def __init__(self, *args, **kwargs):
    group = Group.objects.get(name='Водитель')
    super(DriverAdminForm, self).__init__(*args, **kwargs)
    self.fields['user'].queryset = User.objects.filter(groups__name=group.name)
    self.fields['first_name'] = forms.ModelChoiceField(queryset=User.objects.all())

  class Meta:
    model = AdvancedUser
    fields = ['user', 'patronymic', 'first_name']

But when I start the server, I get -
Unknown field(s) (first_name) specified for AdvancedUser

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question