我正在尝试将“form”作为上下文传递,我的代码:
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,但我收到错误。
答案 0 :(得分:1)
您需要覆盖get_context_data
。{/ p>中的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
。