2

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.

2
  • 2
    What exactly isn't working? Commented Oct 13, 2017 at 6:05
  • if querry=None that will create issue in filter when user open that page without search_res parameter Commented Oct 13, 2017 at 6:23

1 Answer 1

2
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.