vivek sinha
vivek sinha

Reputation: 13

Get data from Django model(mysql) as per user search

I want to get data from Django model(mysql) as per user input. Like I have a html search tab where user will put search value which should get related data from Django-model and display in another html page. I tried but getting failed . Please help..

views.py

 from django.shortcuts import render_to_response
 from django.http import HttpResponse
 from hello.models import Techstop 
 # Create your views here.

 def search(request):
      return render_to_response('search.html')


 def results(request):
    if 'q' in request.GET and request.GET['q']:
            q=request.GET['q']
            name=Techstop.objects.filter(City=q)
            return render_to_response('results.html')
    else:
            return HttpResponse('Please enter a valid input.')


  models.py

  from django.db import models


  class Techstop(models.Model):
          Name = models.CharField(max_length=30)
          Email = models.CharField(max_length=50)
          City = models.CharField(max_length=20)
          Country = models.CharField(max_length=20)
          Dept = models.CharField(max_length=30)

    def __unicode__(self):
          return self.City


       search.html


     <!DOCTYPE html>
  <html>
  <head>
      <title>Search</title>
  </head>
  <body>
  <form action="/search/" method="get">
      <input type="text" name="q">
      <input type="submit" value="Search">
   </form>
  </body>
  </html>

   results.html

  {% if name %}
<ul>
    {% for n in name %}
    <li>{{ n.City }}</li>
    {% endfor %}
</ul>
 {% else %}
      <p>No name matched your search criteria.</p> 
 {% endif %}

Upvotes: 1

Views: 1608

Answers (3)

Soheil__K
Soheil__K

Reputation: 642

you can simply do this using below functions:

import re
from django.db.models import Q

def normalize_query(query_string,
                    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                    normspace=re.compile(r'\s{2,}').sub):

    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 

def get_query(query_string, search_fields):
    ''' Returns a query, that is a combination of Q objects. That combination
        aims to search keywords within a model by testing the given search fields.

    '''
    query = None # Query to search for every search term        
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None # Query to search for a given term in each field
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query

Usage Example:

def search(request):
    if request.method == 'GET':
        if request.GET.get("submit_search_button"): # if search submit button clicked
            query_string = ''
            found_entries = None
            if ('q' in request.GET) and request.GET['q'].strip():
                query_string = request.GET['q']

                entry_query = get_query(query_string, ['name', 'email','city','country','dept'])

                found_entries = Techstop.objects.filter(entry_query)


            return render_to_response('search.html',
                          { 'query_string': query_string, 'found_entries': found_entries },
                          context_instance=RequestContext(request))


    return HttpResponseNotAllowed('only GET here for example!!')

hope it helps!!

Upvotes: 0

binu.py
binu.py

Reputation: 1216

Assuming you are using GET method to submit your form:

def results(request):
    q = request.GET.get('q', None)
    if q:
        # icontains work similar to LIKE keyword in mysql.
        # for exact text search you can directly search City=q
        name=Techstop.objects.filter(City__icontains=q)

        # {'name': name} is the context that we attach with the html to render.
        return render_to_response('results.html', {'name': name})
    else:
        return HttpResponse('Please enter a valid input.')

You can also use Q object for more comples search.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599758

When rendering any template, you need to pass all the variables it needs as the context dictionary.

return render_to_response('results.html', {'name': name})

This is all explained in the tutorial; you should probably go and follow it.

Upvotes: 0

Related Questions