Django-filter: Using Choicefilter With Choices Dependent On Request
I am using django-filter and need to add a ChoiceFilter with choices dependent on the request that I receive. I am reading the docs for ChoiceFilter but it says: This filter matche
Solution 1:
I've been looking too hard that I found two different ways of doing it! (both by overriding the __init__
method). Code inspired from this question.
classLayoutFilterView(filters.FilterSet):
supplier = filters.ChoiceFilter(
label=_('Supplier'), empty_label=_("All Suppliers"),)
def__init__(self, *args, **kwargs):
super(LayoutFilterView, self).__init__(*args, **kwargs)
# First Method
self.filters['supplier'].extra['choices'] = [
(supplier.id, supplier.id) for supplier in ourSuppliers(request=self.request)
]
# Second Method
self.filters['supplier'].extra.update({
'choices': [(supplier.id, supplier.name) for supplier in ourSuppliers(request=self.request)]
})
The function ourSuppliers
is just to return a QuerySet to be used as choices
defourSuppliers(request=None):
if request isNone:
return Supplier.objects.none()
company = request.user.profile.company
return Supplier.objects.filter(company=company)
Post a Comment for "Django-filter: Using Choicefilter With Choices Dependent On Request"