简体   繁体   中英

Set initial value with django-filters?

When using the django-filters app, how can I set the initial value of the field in my filter?

Usually with a standard form in Django , for example a simple selection list form:

class MyForm(forms.Form):
    OPTIONS=(('APP','Apple'),('BAN','Banana')) 
    country = forms.ChoiceField(widget=forms.Select(),
                                         choices=OPTIONS, initial='BAN')

to initialise the forms entry to Banana . However, in my filter.py if I have something like:

class MyFilter(django_filters.FilterSet):
    OPTIONS=(('APP','Apple'),('BAN','Banana')) 
    myfield = django_filters.ChoiceFilter(
             widget=django_filters.widgets.forms.Select(),choices=OPTIONS)
    .
    .

where do I put the initial='BAN' to get the initially selected element of the dropdown etc? I tried the ChoiceFilter arguments and Select() arguments to no avail.

I thought the idea of Filters was to mirror very closely the behaviour of Forms only with the added benefit of filtering obviously, so I'm surprised initialising in (to what seems to me) the intuitive place does not work.

This works for me. It sets a default if no data is provided in the request:

data = request.GET.copy()
if len(data) == 0:
    data['field'] = initial_value
filters = MyFilterSet(data)

Using the same approach as user1867622, I use:

get_query = request.GET.copy()
if 'status' not in get_query:
    get_query['status'] = 'final'
sfilter = MatterFilterSet(get_query, queryset=matters)

Unlike the other answers I would do it by not changing the data from the request.GET , but modifying directly the queryset:

def get_filterset_kwargs(self, filterset_class):
    kwargs = super().get_filterset_kwargs(filterset_class)
    if kwargs['data'] is None:
        kwargs['queryset'] = kwargs['queryset'].filter(myfield ='BAN')
    return kwargs

I use this approach because by changing the kwargs['data'] from request.GET to a dict , you loose the getlist method and can just retrieve one value per key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM