0

我正在尝试将“表单”作为上下文传递,我的代码:

class BlogSearchView(ListView):
    model = Blog
    paginate_by = 20
    template_name = "base/blog_search.html"

    def get_queryset(self):
        qset = super(BlogSearchView, self).get_queryset()
        new_data = self.request.GET.copy()
        form = BlogSearchForm(new_data)
        if form.is_valid():
            search_term = form.cleaned_data['q']#>> how to insert this in template
            if search_term:
                qset = qset.filter(Q(title__icontains=search_term)|
                                   Q(body__icontains=search_term))
            else:
                qset = []
        else:
            form = BlogSearchForm() #>> how to insert this in template
        return qset

尝试使用 get_context_data 但我收到错误。

4

1 回答 1

1

你需要覆盖get_context_data你的BlogSearchView.

快速解决方案:

class BlogSearchView(ListView):

    def get_queryset():
        ...
        #Your queryset definition
        self.search_term = search_term
        self.form = form
        return qset

    def get_context_data(self, **kwargs):
        context = super(BlogSearchView, self).get_context_data(**kwargs)
        context['search_term'] = self.search_term
        context['form'] = self.form
        return context

然后你可以在模板中使用search_term和。form

于 2013-04-22T09:36:14.793 回答