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


  {% for post in posts %}  
  {{ post.title }}
  {% endfor %}

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




  Homepage




  All Posts

    {% for post in posts %}  
      {{ post.title }}
    {% endfor %}


   Posts by Query






    // 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();
      }
    });


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

146 7 7 0