@
@
@bickford2018-09-03 14:59:18
Django
@bickford, 2018-09-03 14:59:18

How to create a dynamic selection for M2M in the admin panel?

There are models:

class A(models.Model):
    title = models.CharField()

class B(models.Model):
    category = models.ForeignKey(A)
    title = models.CharField()

class C(models.Model):
    category = models.ForeignKey(A)
    products = models.ManyToManyField(B)

In the admin panel, I change model C.
How to select M2M links to model B, display only those instances of B that are tied to the already selected model A?
Ideally, I want to understand how to make choice A just a formality, without creating a real string on it.
What I managed to find is clearly not enough for me. I tried to create a form, bind it in admin.py.
class MyForm(forms.ModelForm):

    class Meta:
        model = C
        fields = ('category', 'products')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        category = ???
        self.fields['products'].queryset = category.products.all()

How can I get the category (model A) that I have chosen?
It feels like I'm somewhere very close to the solution, but I can't think of anything.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2018-09-04
_

This is done on the frontend, for example using django-select2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question