Django-filter: Passing an initial value

Created on 28 Aug 2014  Â·  5Comments  Â·  Source: carltongibson/django-filter

I've tried to pass an initial value to the form by separately trying the following methods (yadda being a placeholder value):

#views.py
def operator_search(request):
    operators = Operator.objects.all()
    f = OperatorFilter(request.GET, initial={'operator_city':'yadda'}, queryset=Operator.objects.all())
    return render(request, 'vendors/operator_search.html', {'filter':f, 'operators':operators})
#forms.py
class OperatorFilter(django_filters.FilterSet):
     operator_city = django_filters.CharFilter(initial="yadda")
     class Meta:
         model = Operator

Neither seems to work. How can I set an initial value for the form when using django-filters?

Most helpful comment

in case of ChoiceField you can use:
empty_label=None, null_value=<default-value>, null_label=<default-label>

All 5 comments

I'm wondering this as well, I dove through the different Filter, FilterSet, and Form objects and didn't find a decent way to do this. I don't believe initial will work because it is using a bound form, although I didn't find a good work around passing the data itself. I found a workaround through the QueryDict and passing that to the FilterSet but there has to be a cleaner way to do this.

Would you mind posting a snippet of your workaround? I'm kind of stuck at this point and my users are tired of having their searches default to Afghanistan :)

Hi @chromakey — I think this is a usage question so it's better aimed at the Mailing List.

However, the form's data is just that passed to the FilterSet, so if I understand you correctly you should be able to do something like this:

initial = {'operator_city':'yadda'}
initial.update(request.GET)
f = OperatorFilter(initial, ...)

If that's not it please follow up and explain more on the Mailing List. Thanks.

I searched the mailing list but could not find a solution. Here is a workaround that I figured out (use at your own discretion):

 ####### WARNING: this is a hack to enable initial filter field selection in django-filters########
# Create a mutable QueryDict object, default is immutable
initial = QueryDict('active_study=True', mutable=True)
# QueryDict update works different than normal dictionary update. Refer to docs.
initial.update(request.GET)
# Place the hacked, mutable QueryDict to the FilterSet.
filter = StudyFilter(initial, queryset=Study.objects.all())

in case of ChoiceField you can use:
empty_label=None, null_value=<default-value>, null_label=<default-label>

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jwineinger picture jwineinger  Â·  3Comments

madelyneriksen picture madelyneriksen  Â·  4Comments

sassanh picture sassanh  Â·  4Comments

techdragon picture techdragon  Â·  5Comments

lalzada picture lalzada  Â·  3Comments