使用Django 1.9和Python 3.5,我想做一个简单的搜索表单:
views.py
from django.views import generic
from django.shortcuts import render
from .models import Movie, Genre
class IndexView(generic.ListView):
template_name = 'movies/index.html'
page_template = 'movies/all_movies.html'
context_object_name = 'all_movies'
model = Movie
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context.update({
'all_genres': Genre.objects.all(),
'page_title': 'Latest'
})
return context
def get_queryset(self):
query = request.GET.get('q')
if query:
return Movie.objects.filter(title__icontains=query)
else:
return Movie.objects.all()
形式
<form method="GET" action="" id="searchform">
<input class="searchfield" id="searchbox" name="q" type="text" value="{{ request.GET.q }}" placeholder="Search..."/>
</form>
出于某种原因,我不断收到错误:
名称'request'未定义
我不太确定我做错了什么,任何帮助都会受到赞赏。
答案 0 :(得分:3)
您似乎认为该错误并非来自您的模板。它来自你的观点
def get_queryset(self):
query = request.GET.get('q')
应该是
query = self.request.GET.get('q')