带有表单的基于 Django 类的视图 ListView [英] Django class based view ListView with form
问题描述
主视图是一个简单的分页 ListView,我想向其中添加一个搜索表单.
The main view is a simple paginated ListView and I want to add a search form to it.
我认为这样的事情可以解决问题:
I thought something like this would do the trick:
class MyListView(ListView, FormView):
form_class = MySearchForm
success_url = 'my-sucess-url'
model = MyModel
# ...
但显然我弄错了..而且我在官方文档中找不到如何做.
But apparently I got it wrong .. and I can't find how to do it in the official documentation.
建议?
推荐答案
这些答案对引导我走向正确的方向大有帮助.谢谢各位.
These answers have helped so much to steer me in the right direction. Thank guys.
对于我的实现,我需要一个在 get 和 post 上都返回 ListView 的表单视图.我不喜欢重复 get 函数的内容,但它需要进行一些更改.现在也可以从 get_queryset 使用 self.form 获取该表单.
For my implementation I needed a form view that returned a ListView on both get and post. I don't like having to repeat the contents of the get function but it needed a couple of changes. The form is now available from get_queryset now too with self.form.
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
# ...
这篇关于带有表单的基于 Django 类的视图 ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!