Search code examples
djangodjango-formsdjango-templatesdjango-admindjango-filter

Filtering ManyToMany in Django-Admin/Django-Form by related field


I want to filter my ManyToMany by related fields in the Django-Admin (create/edit object). For example i have 3 Models:

Model 1 - Boardgame: Name (CharField), Genre (ForeignKey) Model 2 - Location: Name (CharField), Boardgame (ManyToMany) Model 3 - Genre: Name (CharField)

Now in the django-admin when i edit a location i can add and remove boardgames via horizontal-filter. Now i want an extra select Field where i can define a genre, so the manyToMany choices change based on what i select on the genre-select.

But i can't find an option to

  1. Include the genre-select
  2. To filter by the genre-select

Anyone here having an idea, how to solve this?

What i tried so far:

  1. Tried the django_advanced_filter because google lead me to it -> It is just for filtering in the "overview"-tab
  2. Tried to find a function that can do this natively in the admin -> Didn't find anything
  3. Had the idea to accomplish this via a modelsForm but wasn't able to find a possibility to add there a filter tab.
  4. Read something about django_filters, that maybe an option, but didnt find a possibility to integrate it in the forms.py

Solution

  • Did you have a look at the django-formset package?

    From reading your question, this example https://django-formset.fly.dev/dual-selector/#filtering-select-options shows what you're probably looking for.