Django ChoiceFilter选择框的初始(默认)值

时间:2015-07-30 07:29:30

标签: python django django-forms

我正在尝试在由DjangoFilter ChoiceFilter (更多信息here)创建的选择框中设置初始,默认值。代码似乎很简单:

class MyFilter(FilterSet):
    CHOICES = (
        ('', 'Any'),
        ('closed', 'Closed'),
        ('new', 'New'),
    )

    my_select_box = ChoiceFilter(choices=CHOICES, initial='new')

    class Meta:
        model = MyModel
        fields = ('my_select_box')

    def __init__(self, *args, **kwargs):
        super(MyFilter, self).__init__(*args, **kwargs)
        self.form.helper = FormHelper()
        self.form.helper.form_method = 'get'
        self.form.helper.add_input(Submit('submit', 'Search'))
        self.form.helper.form_class = 'form-inline'
        self.form.helper.field_class = 'm-r m-b-sm'
        self.form.helper.label_class = 'm-r'

在views.py上:

class MyView(BaseListView):
    content_template = "template.html"
    model = MyModel
    filter_class = MyFilter
    table_class = MyTable

class BaseListView(BaseView, MultipleObjectMixin, SingleTableMixin):
    table_class = None
    filter_class = None
    queryset = None
    list = None
    dictionary = {}

    def get_context_data(self, **kwargs):
        if self.list is not None:
            self.object_list = self.list
        else:
            if self.queryset is None:
                self.queryset = self.get_queryset()
            self.object_list = self.queryset

        if self.filter_class is not None:
            filter = self.filter_class(self.request.GET, queryset=self.object_list)
            table = self.table_class(filter.qs)
            # filter.form.fields['my_select_box'].default = 'new'
            # filter.form.initial['my_select_box'] = 'new'
            ids = json.dumps(list(filter.qs.values_list('id', flat=True)))
        else:
            filter = ""
            table = self.table_class(self.object_list)
            ids = [obj['id'] for obj in self.object_list] if self.object_list is list else None

        RequestConfig(self.request, paginate={"per_page": 10}).configure(table)
        kwargs['content'] = render_to_string(self.content_template, context_instance=RequestContext(self.request),
                                             dictionary=dict(
                                                 {'filter': filter, 'object_list': self.object_list, 'ids_list': ids,
                                                  'table': table}.items() + self.dictionary.items()))
        context = super(BaseListView, self).get_context_data(**kwargs)
        return context

在template.html上:

<div class="panel-body">
        <section class="panel panel-default">
            <header class="panel-heading font-bold">
                Filter
            </header>
            <div class="panel-body">
                {% crispy filter.form %}
            </div>
        </section>
    {% render_table table %}
</div>

在模板方面,我可以通过调试器看到form.my_select_box.initial设置为&#39; new&#39;。但是,它不起作用(而不是'new'我也尝试整数)。如果我将CHOICES更改为:

CHOICES = (
    ('any', 'Any'),
    ('closed', 'Closed'),
    ('', 'New'),
)

它似乎有效 - 但我没有从&#34; New&#34;选择,这会使事情变得粗糙 - 我当然可以通过编辑将我的''值变为'new',并'any'在views.py的后端变为'' request.GET(虽然不是很好的解决方案),但是如果我使用页面刷新后,我会看到的结果,但选择会显示任意 (和相反)。

我相信解决方案可以在服务器端实现(我不想要JS)?

0 个答案:

没有答案