mari mari - 1 year ago 106
Python Question

Django - Simple search form

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

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)
'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)
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..."/>

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 Source

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') 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download