一尘不染

带有表单的基于Django类的视图ListView

django

主视图是一个简单的分页ListView,我想向其中添加搜索表单。

我认为这样可以解决问题:

class MyListView(ListView, FormView):
    form_class = MySearchForm
    success_url = 'my-sucess-url'
    model = MyModel
    # ...

但是显然我错了..我在官方文档中找不到该怎么做的方法。

建议?


阅读 688

收藏
2020-03-29

共1个答案

一尘不染

这些答案对引导我朝正确的方向大有帮助。谢谢大家

对于我的实现,我需要一个窗体视图,该窗体视图同时在get和post上返回ListView。我不喜欢重复get函数的内容,但需要进行一些更改。现在,self.form也可以从get_queryset获得该表单。

from django.http import Http404
from django.utils.translation import ugettext as _
from django.views.generic.edit import FormMixin
from django.views.generic.list import ListView

class FormListView(FormMixin, ListView):
    def get(self, request, *args, **kwargs):
        # From ProcessFormMixin
        form_class = self.get_form_class()
        self.form = self.get_form(form_class)

        # From BaseListView
        self.object_list = self.get_queryset()
        allow_empty = self.get_allow_empty()
        if not allow_empty and len(self.object_list) == 0:
            raise Http404(_(u"Empty list and '%(class_name)s.allow_empty' is False.")
                          % {'class_name': self.__class__.__name__})

        context = self.get_context_data(object_list=self.object_list, form=self.form)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        return self.get(request, *args, **kwargs)


class MyListView(FormListView):
    form_class = MySearchForm
    model = MyModel
    # ...
2020-03-29