carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections
https://django-filter.readthedocs.io/en/main/
Other
4.45k stars 769 forks source link

Passing an initial value #160

Closed chromakey closed 10 years ago

chromakey commented 10 years ago

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?

jranck88 commented 10 years ago

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.

chromakey commented 10 years ago

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 :)

carltongibson commented 10 years ago

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.

jiangbotang commented 8 years ago

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())
depaolim commented 7 years ago

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