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 beforeis_valid
field, but with no result.
Answer
This is a very common use case when dealing with ModelForm
s. The problem is that in the form fields ModelChoice
and ModelMultipleChoiceField
, which are used respectively for the model fields ForeignKey
and ManyToManyField
,
it defaults the queryset to the Model.objects.all()
.
If the filtering was static, you could simply pass a filtered queryset in the form definition, like
Model.objects.filter(status='pending')
.
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.
models.py
Here is how we can create a ModelForm
for the Product
model, using only the currently logged-in user:
forms.py
That means now the ProductForm
has a mandatory parameter in its constructor. So, instead of initializing the form
as form = ProductForm()
, you need to pass a user instance: form = ProductForm(user)
.
Here is a working example of view handling this form:
views.py
Using ModelFormSet
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:
models.py
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.