<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=338168267432629&amp;ev=PageView&amp;noscript=1">

Django search function using JQuery Ajax

In this example, I am going to show how to create a search function in Django using JQuery Ajax. This is a simple way to display results of a search query without reloading the current page or navigating to the another page. We are going to use the Users table …


In this example, I am going to show how to create a search function in Django using JQuery Ajax. This is a simple way to display results of a search query without reloading the current page or navigating to the another page. We are going to use the Users table which Django generates when doing a ‘python manage.py syncdb’ for the first time.

Step 1: Create an app.

Assuming that we have an existing project, we will start by creating our search app.

‘python manage.py startapp ajaxsearch’ this will create a folder ajaxsearch with files inside.

Step 2: Open the views.py inside the folder ajaxsearch

Edit views.py and insert the following code:

from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.db.models import Q
from django.contrib.auth.models import User
import time

def index( request ):
    return render_to_response( 'index.html', {}, context_instance = RequestContext( request ) )

def ajax_user_search( request ):

    if request.is_ajax():
        q = request.GET.get( 'q' )
        if q is not None:            
            results = User.objects.filter( 
                Q( first_name__contains = q ) |
                Q( last_name__contains = q ) |
                Q( username__contains = q ) ).order_by( 'username' )

            return render_to_response( 'results.html', { 'results': results, }, 
                                       context_instance = RequestContext( request ) )

The ‘ajax_user_search’ function is called everytime we do a search query (when clicking the submit button).

What it does is search for any matches from the value given by the user against the data in the Users table. ‘q’ is the variable that contains the value given.

Step 3: create a file urls.py inside the ‘ajaxsearch’ folder.

Insert the following code:

from django.conf.urls.defaults import *
from ajaxsearch.views import *

urlpatterns = patterns( '',
         url( r'^
url( r'^users/
                              )

This url pattern ‘url( r’^users/$’, ajax_user_search, name = ‘demo_user_search’ )’ will be used to call the function ‘ajax_user_search’ in our views.py.

Add this line of code to your urls.py in the project root:

( r'^search/', include( 'ajaxsearch.urls' ) ),

my urls.py looks like this:

from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url( r'^search/', include( 'ajaxsearch.urls' ) ),
)

urlpatterns += patterns('',
    (r'^media/(?P.*)

Step 4: Create the templates.

Let’s create our html files inside the templates folder. In this example, we will create 3 templates. ‘base.html’, ‘index.html’ and ‘results.html’.

Here is our base.html:

<html>

<head>
<title>Django/jQuery AJAX Search</title>
<link href=”style.css” rel=”stylesheet” type=”text/css” />          <script type=”text/javascript” src=”http://jqueryjs.googlecode.com/files/jquery-1.2.6.js”></script>


    </head>

<body>
<div id=”centered”>



</div>
</body>
</html>

Our base.html will provide the skeleton structure defining elements that will be on every page in the site. It has two blocks (‘block extra_js’ and ‘block main’). ‘

Similar posts

Get notified about the latest in Tech

Be the first to know about new tech from the experts at Bixly!