Michał Strumecki asks:
I just want to filter select field in a form, regarding a currently logged user. Every user has own categories and budgets. I want to display only a models related with a currently logged user. I’ve tried stuff with filtering before
is_validfield, but with no result.
This is a very common use case when dealing with
ModelForms. The problem is that in the form fields
ModelMultipleChoiceField, which are used respectively for the model fields
it defaults the queryset to the
If the filtering was static, you could simply pass a filtered queryset in the form definition, like
When the filtering parameter is dynamic, we need to do a few tweaks in the form to get the right queryset.
Let’s simplify the scenario a little bit. We have the Django
User model, a
Category model and
Product model. Now
let’s say it’s a multi-user application. And each user can only see the products they create, and naturally only use
the categories they own.
Here is how we can create a
ModelForm for the
Product model, using only the currently logged-in user:
That means now the
ProductForm has a mandatory parameter in its constructor. So, instead of initializing the form
form = ProductForm(), you need to pass a user instance:
form = ProductForm(user).
Here is a working example of view handling this form:
The machinery behind the
modelformset_factory is not very flexible, so we can’t add extra parameters in the
form constructor. But we certainly can play with the available resources.
The difference here is that we will need to change the queryset on the fly.
Here is what we can do:
The idea here is to provide a screen where the user can edit all his products at once. The product form involves handling a list of categories. So for each form in the formset, we need to override the queryset with the proper list of values.
The big difference here is that each of the categories list is filtered by the categories of the logged in user.
Get the Code
I prepared a very detailed example you can explore to get more insights.
The code is available on GitHub: github.com/sibtc/askvitor.