A
A
Alexander Vinogradov2020-12-30 11:07:18
Django
Alexander Vinogradov, 2020-12-30 11:07:18

How to get the parent of an inline admin link in a form?

In the admin panel, editing models with inline communication. For the subordinate model, its own form is made. In this form, you need to get a parent. How to do it?
Those. in form A, get parent B
I think it should be clear from the picture.

picture

5e09aff4ec616425652724.jpeg

admin

class CategoriesServicesInline(admin.TabularInline):
    model = cm.CategoriesServices
    extra = 1
    fields = ('name', 'description', 'price', 'explanation', 'group')
    # form = CategoryForm


@admin.register(cm.CategoriesGroups)
class CategoriesGroupsAdmin(admin.ModelAdmin):
    inlines = [
        CategoriesServicesInline,
    ]


@admin.register(cm.Services)
class ServicesAdmin(admin.ModelAdmin):
    inlines = [
        CategoriesServicesInline,
    ]


forms

from django import forms
from core import models as cm


class CategoryForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CategoryForm, self).__init__(*args, **kwargs)

        if self.fields.get('group', None) is not None:
            self.fields['group'].queryset = self.fields['group']\
                .queryset.filter(service_id=self.instance.service_id)

    class Meta:
        model = cm.CategoriesServices
        fields = '__all__'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-12-30
@bacon

Most likely only if in Inline you override the get_form method (if it is there) and in it, directly transfer the parent to the form. But keep in mind that this will only happen when editing the model, when creating it, it doesn’t anymore, since the parent itself has not yet been created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question