Andrea Grandi
Andrea Grandi

Reputation: 975

Filtering a list of values in Django admin field, based on a previous field value selection

In a Django application that I have I'm using these models:

A Client can have only one Agency and an Agency can have many Clients.

When I'm editing/creating a Profile I first select the Agency, then I can select multiple Clients (and this is ok).

My problem is that in the Clients field I see ALL existing Clients, while I would want to see only Clients related to the selected Agency. How can I do this?

Thanks!

Upvotes: 1

Views: 1702

Answers (2)

mbo
mbo

Reputation: 778

If you are editing the profile, you can write a filter for the clients field with "formfield_for_manytomany" https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany or "formfield_for_choice_field".

But for creating a profile it's only possible to change the client list with javascript afaik. Which can be a tricky thing on the admin forms.

Why do you not just select the clients and omit the formfield for the agency? You could validate the selection afterwards with a validator.

Upvotes: 0

ndpu
ndpu

Reputation: 22561

That app can help, i think (Django application to handle chained model fields) - https://github.com/digi604/django-smart-selects

link in pypi - https://pypi.python.org/pypi/django-smart-selects/

Upvotes: 2

Related Questions