[Answered ]-Linking the View / Model in Django to a Javascript Front End Framework

2👍

So I’m suggesting the following with your price slider example in mind. Here’s an example of how to search users by name with just jQuery.

You’ll need an input form for the search query, obviously.

<form class="search-form">
    <input type="text" name="search" placeholder="Search.." id="search-name">
    <button class="search-submit">Go!</button>
    <!-- toggleable search options here, including your price slider. -->
</form>

Customize the look of this however you want. The important thing here is the user will enter text in the search box, and click “Go!”. You’ll want to attach a jQuery event to this action, not submit as a form because that will reload your page, which you don’t want.

$(".search-submit").click(function() {
    var url = "/search?name=" + $("#search-name").val();
    $.ajax({
        method: "GET",
        url: url,
        success: function (data) {
            // Dynamically change your page results with more jquery based on data
        },
        error: function (err) {
            alert("Something went wrong");
        }
    });
});

Next, you need a URL and View to accept this ajax request.

urls.py:

from views.py import search
# Search URL
url((r'^search/$', search),

views.py:

import json
from app.models import User
from django.http import HttpRespons

def search(request):
    # Grab the data
    query = request.GET.get("name", None)
    # Make the query using your backend, the following is just an example
    users = User.objects.filter(name=name)
    # Serialize the objects as necessary
    data = []
    for user in users:
        data.append({
            "name" : user.name,
            "age" : user.age,
            # Other stuff you want from the objects you retrieved.
        })
    return HttpResponse(json.dumps(data))

This closes the loop. When a user enters a search query, the ajax will make a call to your resource, get new results, and I’ll leave the dynamic changing of the page to you.

Things to do:
– some kind of loading “mask” while your query is being fetched. Can be done with jquery and CSS
– Extra search options. Probably best done as more query strings in your request you make to the server. For example, “/search?name=Jack&age=42”.

👤Nick

Leave a comment