用django过滤器设置初始值? [英] Set initial value with django-filters?

查看:157
本文介绍了用django过滤器设置初始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 django-filters 应用程序时,如何设置我的字段的初始值过滤器?



通常使用 Django 中的标准表单,例如一个简单的选择列表形式:

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

将表单条目初始化为香蕉。但是,如果我有这样的东西,在我的 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 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)

这篇关于用django过滤器设置初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆