用django过滤器设置初始值? [英] Set initial value with django-filters?
问题描述
当使用 django-filters 应用程序时,如何设置我的字段的初始值过滤器?
通常使用 Django
中的标准表单,例如一个简单的选择列表形式:
class MyForm(forms.Form):
pre>
OPTIONS =(('APP','Apple'),('BAN' 'Banana'))
country = forms.ChoiceField(widget = forms.Select(),
choices = OPTIONS,initial ='BAN')
将表单条目初始化为
香蕉
。但是,如果我有这样的东西,在我的filter.py
中:MyFilter(django_filters.FilterSet):
OPTIONS =(('APP','Apple'),('BAN','Banana'))
myfield = django_filters.ChoiceFilter(
widget = django_filters.widgets.forms.Select(),choices = OPTIONS)
。
。
我在哪里放置
initial ='BAN'
获取下拉列表的最初选择的元素等?
我尝试了ChoiceFilter
参数和Select()
参数无效。
我认为
过滤器
的想法是非常密切地反映Forms
的行为只有过滤的附加效益显然,所以我很惊讶(在我看来似乎),直觉的地方不起作用。解决方案这对我有用如果请求中没有提供数据,则设置默认值:
data = request.GET.copy()
如果len(data)== 0:
data ['field'] = initial_value
filters = MyFilterSet(data)
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 myfilter.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 theChoiceFilter
arguments andSelect()
arguments to no avail.I thought the idea of
Filters
was to mirror very closely the behaviour ofForms
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)
这篇关于用django过滤器设置初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!