0

Hello guys and welcome back, this night i want to share a simply tutorial how to Implement Realtime Search using Django and Ajax. Lets goo… ^_^

1. yourapp/models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()

2. yourapp/views.py

from django.shortcuts import render
from django.db.models import Q
from yourapp.models import Post

def homepage(request):
    posts = Post.objects.all()
    return render(
        request, 'yourapp/search.html',
        {'posts': posts}
    )

def search(request):
    query = request.GET.get('q')
    if query is not None and query != '' and request.is_ajax():
        posts = Post.objects.filter(  
            Q(title__icontains=query)
        )

        # you also can limit the maximum of `posts` here.
        # eg: posts[:50]
        return render(
            request, 'yourapp/snippets/search.html',
            {'posts': posts}  
        )
    return render(
        request, 'yourapp/snippets/search.html'  
    )

3. yourapp/urls.py

from django.conf.urls import url

from yourapp.views import (homepage, search)

urlpatterns = [
    url(r'^$', homepage, name='homepage'),
    url(r'^search/$', search, name='search'),
]

4. ../templates/yourapp/snippets/search.html

<ul id="results-search">
  {% for post in posts %}  
  <li><a href="#">{{ post.title }}</a></li>
  {% endfor %}
</ul>

5. ../templates/yourapp/homepage.html

<!DOCTYPE html>  
<html>
<head>
  <title>Homepage</title>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>

<body>
  <h1>All Posts</h1>
  <ul>
    {% for post in posts %}  
      <li><a href="#">{{ post.title }}</a></li>
    {% endfor %}
  </ul>
  <hr />
   <h1>Posts by Query</h1>
   <input id="search-input" type="text" placeholder="Type to search posts..."/>
   <div id="main-results-search"></div>
</body>

<footer>
  <script type="text/javascript">
    // Implement realtime search with `keyup` function.

    $('#search-input').keyup(function (event) {
      var query =($('#search-input").val());

      if (query != '' || query != ' ') {  
        $.ajax({
           type: 'GET',
           url: '{% url "search" %}',
           data: {
             'csrfmiddlewaretoken': '{{ csrf_token }}',
             'q': query
           },
           success: function(data) {
              $('#main-results-search').html(data);
           },
           error: function(data) {
              console.log(data);
           }
         });
      }
    });

    // Removing the element after search
    // and when user clicked another/outside of this element below.

    $(document).click(function(event) {
      $is_inside = $(event.target).closest('#main-results-search').length;

      if( event.target.id == 'search-input' || $is_inside ) {
        return;
      }else {
        $('#results-search').remove();
      }
    });
  </script>
</footer>

Simple right? ^_^, any question? please comment below.. :D

django python tricks ajax

Your Answer

blog comments powered by Disqus