mari mari - 2 months ago 22
Python Question

Django - Simple search form

Using Django 1.9 with Python 3.5, I would like to make a simple search form:

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

<form method="GET" action="" id="searchform">
<input class="searchfield" id="searchbox" name="q" type="text" value="{{ request.GET.q }}" placeholder="Search..."/>
</form>


For some reason I keep getting the error:


name 'request' is not defined


I'm not quite sure what I'm doing wrong, any help would be appreciated.

Answer

That error does not come from your template as you seem to think. It comes from your view

def get_queryset(self):
    query = request.GET.get('q')

It should be

    query = self.request.GET.get('q') 
Comments