Set initial value using django filters?

When using django-filters , how can I set the initial value of a 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 initialize writing forms to Banana. However, in mine 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 initial='BAN'to get the initially selected item in the dropdown list, etc.? I tried the arguments ChoiceFilterand to Select()no avail.

, Filters , Forms , , , ( ) .

+4
3

. , :

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

, user1867622, ​​ :

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

, , request.GET, :

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

, , kwargs['data'] request.GET dict, getlist .

0

Source: https://habr.com/ru/post/1527390/


All Articles