haystack
Search is an essential tool for any website, and is a feature often requested by both site owners and users. While the built-in Django QuerySet...
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.
{%- endset -%} {%- blog_post_data_wall_wrapper body={{hs_blog_post_body}}, summary={{hs_blog_post_summary}} %}Search is an essential tool for any website, and is a feature often requested by both site owners and users. While the built-in Django QuerySet...
Here’s a Django tutorial on registration. Registration allows you to have users. A weak registration system puts your site at risk of spammers...
One of the awesome things that Django offers us is it lets us use our Google account as authentication to the website that we are building. I am...