3
votes

I've the following django-filter (https://github.com/alex/django-filter/) filter:

class ApplicationFilter(django_filters.FilterSet):
    status = django_filters.ChoiceFilter(choices=STATUS2,)

with status containing the following tuple list:

STATUS_CHOICES = (
    ( '', u'All'),
    ( 'NEW', u'New'),
    ( 'SUBMIT', u'Submit'),
    ( 'CANCEL', u'Cancel'),
)

Now, I'd like to set an initial value for that filter different than the empty one (All). So I tried the following things, all without success:

i. Adding an initial parameter to the field: status = django_filters.ChoiceFilter(choices=STATUS2, initial = 'NEW' ) or with an array status = django_filters.ChoiceFilter(choices=STATUS2, initial = ['NEW'] ). The form rendered with the default initial value.

ii. Modifying the __init__ of the form:

    def __init__(self, *args, **kwargs):
        super(ApplicationFilter, self).__init__(*args, **kwargs)
        self.form.initial['status']='NEW'
        self.form.fields['status'].initial='NEW'
-- again the form rendered with the default initial value (All)... Also tried setting the value as ['NEW'] -- again no luck.

Does anybody know how should this be handled ? I am using the latest (from github) version of django-filter.

TIA

2
Try to call parent method __init__ after set initial values. - qwetty
Should I call it again ? I already call it once ! - Serafeim
No, no again. Just move this super(...) line to the end. I never had a problem with that. I looked into one of my project and I call it at the end. I'm not sure if it's a solution for your problem. - qwetty
self.form is throwing an exception if I put it after the super line after. I did just a print self.form before super() and got: AttributeError: 'ApplicationFilter' object has no attribute 'filters' - Serafeim
Did you find a solution for this? - javiercf

2 Answers

0
votes

Try this:

def __init__(self, *args, **kwargs):
    super(ApplicationFilter, self).init(*args, **kwargs)
    self.initial['status'] = 'NEW'
0
votes

This answer might work for you: Set initial value with django-filters?

In my views, I do:

get_query = request.GET.copy()
if 'status' not in get_query:
    get_query['status'] = 'final'
filter_set = MatterFilterSet(get_query)