基于Django类的视图ListView与表单

时间:2011-06-20 03:24:30

标签: django views

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

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

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

但显然我弄错了......我在官方文档中找不到如何做到这一点。

建议?

5 个答案:

答案 0 :(得分:30)

这些答案帮助我引导我朝着正确的方向前进。谢谢你们。

对于我的实现,我需要一个表单视图,在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
    # ...

答案 1 :(得分:6)

我一直在寻找合适的解决方案。但是我找不到任何东西,所以不得不想出自己的。

<强> views.py

class VocationsListView(ListView):

    context_object_name = "vocations"
    template_name = "vocations/vocations.html"
    paginate_by = 10

    def get_queryset(self):
        get = self.request.GET.copy()
        if(len(get)):
            get.pop('page')
        self.baseurl = urlencode(get)
        model = Vocation
        self.form = SearchForm(self.request.GET)
        filters = model.get_queryset(self.request.GET)
        if len(filters):
            model = model.objects.filter(filters)
        else:
            model = model.objects.all()
        return model



def get_context_data(self):
    context = super(VocationsListView, self).get_context_data()
    context['form'] = self.form
    context['baseurl']= self.baseurl
    return context

<强> models.py

class Vocation(models.Model):
    title = models.CharField(max_length = 255)
    intro = models.TextField()
    description = models.TextField(blank = True)
    date_created = models.DateTimeField(auto_now_add = True)
    date_modified = models.DateTimeField(auto_now = True)
    created_by = models.ForeignKey(User, related_name = "vocation_created")
    modified_by = models.ForeignKey(User, related_name = "vocation_modified")

    class Meta:
        db_table = "vocation"

    @property
    def slug(self):
        return defaultfilters.slugify(self.title)

    def __unicode__(self):
        return self.title

    @staticmethod
    def get_queryset(params):

        date_created = params.get('date_created')
        keyword = params.get('keyword')
        qset = Q(pk__gt = 0)
        if keyword:
            qset &= Q(title__icontains = keyword)
        if date_created:
            qset &= Q(date_created__gte = date_created)
        return qset

所以基本上我将这段代码添加到每个模型类中,我想在其中实现搜索功能。这是因为必须明确准备每个模型的过滤器

@staticmethod
def get_queryset(params):

    date_created = params.get('date_created')
    keyword = params.get('keyword')
    qset = Q(pk__gt = 0)
    if keyword:
        qset &= Q(title__icontains = keyword)
    if date_created
        qset &= Q(date_created__gte = date_created)
    return qset

它准备了我用来从模型中检索数据的qset过滤器

答案 2 :(得分:1)

根据之前的回答,这是我对用于在ListView所在页面上显示表单的视图的看法:

class IndexView(FormMixin, ListView):
    ''' Homepage: displays list of links, and a form used to create them '''
    template_name = "links/index.html"
    context_object_name = "links"
    form_class = LinkForm

    def get_queryset(self):
        return Links.objects.all()

def add_link(request):
    # Sole job of this function is to process the form when POSTed. 
    if request.method == "POST":
        form = LinkForm(request.POST)

        if form.is_valid():
            Links.objects.create(address=form.cleaned_data['address'])

        return HttpResponseRedirect('/')

然后,最后一件事就是将add_link视图函数绑定到表单的action url,我觉得你很高兴。

答案 3 :(得分:0)

the official documentation中介绍了使用mixins向索引视图和列表视图添加表单的方法。

文档通常建议不要使用这种方法。建议改写一些Python,然后手动编写视图。

答案 4 :(得分:0)

在Django 2.2中,您可以执行此操作(至少在get-请求下可以正常工作):

from django.views.generic import ListView
from django.views.generic.edit import FormMixin

from .models import Property
from .forms import SearchForm

class ListPageView(FormMixin, ListView):
    template_name = 'property_list.html'
    model = Property
    form_class = SearchForm
    queryset = Property.objects.all()

FormMixin之前使用ListView。如果您想在SearchForm中使用TemplateView,可以执行以下操作:

from django.views.generic.base import TemplateView
from django.views.generic.edit import FormMixin

from .models import Property
from .forms import SearchForm

class HomePageView(FormMixin, TemplateView):
    template_name = 'home.html'
    form_class = SearchForm