Answer the question
In order to leave comments, you need to log in
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 = 'Данные водиетелей'
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
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']
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 questionAsk a Question
731 491 924 answers to any question