Florian
Florian

Reputation: 35

Django Querying database based on the user input

I just started learning python/django and I'm working on a small project. I have models and an html form build. How can I query my database and filter all the names of the drivers that matches the destination city the user entered.

My models

class Drivers(models.Model):
    first_name = models.CharField(max_length=30, null=True, blank=False)
    last_name = models.CharField(max_length=30, null=True, blank=False)
    destination_one = models.CharField(max_length=50, null=True, blank=False)

My HTML form

<form id="searchform"  method="get" action="" accept-charset="utf-8">
  Search destination:
  <input id="searchbox" name="search_res" type="text" placeholder="Search">
  <input type="submit" value="OK">
</form>

    {% for dr in results %}

        {{dr.first_name}}
        {{dr.last_name}}
        {{dr.destination_one}}
        <br>

    {% endfor %}

    <br>

My View

def newpage(request):
    query = request.GET.get('search_res')
    if request.method == 'GET':
        results = Drivers.objects.filter(destination_one=query)
        context = RequestContext(request)
    return render_to_response(request,'busapp/newpage.html',{'results': results})

Models and HTML are fine. I'm having trouble building a simple def in views.py.

Upvotes: 2

Views: 1783

Answers (1)

Neeraj Kumar
Neeraj Kumar

Reputation: 3941

from django.shortcuts import render
def newpage(request):
    query = request.GET.get('search_res', None)
    context = {}

    if query and request.method == 'GET':
        results = Drivers.objects.filter(destination_one=query)
        context.update({'results': results})
return render(request,'busapp/newpage.html',context)

Upvotes: 2

Related Questions