简体   繁体   中英

Jquery drop down list in Django

I am trying to learn using Jquery in django application.My code looks like this

views.py

from django.shortcuts import render
from django.http import HttpResponse
from airapp.models import Travel


def search_form(request):
    return render(request, 'search_form.html')


def searchs(request):
    if 'tr' in request.GET and request.GET['tr']:
        q = request.GET['tr']


        books = Travel.objects.filter(froms__icontains=q)
        return render(request, 'search_results.html',
            {'books': books, 'query': q})
    else:
        return HttpResponse('Please submit a search term.')  

search_form.html

<html>
<head>
    <title>Search</title>
</head>
<body>
<form id="travel-form">    
        TRAVEL<select name='tr'>
    <option value='one' >ONE WAY</option>
    <option value='two'>TWO WAY</option>

    </select>
        </form>


    <div id='one' >
    </div>
</body>
</html>

search_results.html

<p>You searched for: <strong>{{ query }}</strong></p>

{% if books %}
    <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
    <ul>
        {% for book in books %}
        <li>{{ book.froms }}</li>
        <li>{{ book.to}}</li>
        <li>{{ book.classs }}</li>
        <li>{{ book.details }}</li>

        {% endfor %}
    </ul>
{% else %}
    <p>No books matched your search criteria.</p>
{% endif %}

urls.py

from django.conf.urls import patterns, include, url
from air import views

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',

    url(r'^admin/', include(admin.site.urls)),
    url(r'^search-form/$', views.search_form),
    url(r'^search/$', views.search),
)

when I select an option from TRAVEL drop down list either 'one' or 'two' I want to display search results on the same page where form is created(search_form.html) .Can I display it using jquery? Can anybody help me to write the code.

When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:


JQuery function, placed in the templated you need, in your case (search_form.html)

function search_results(){       
    //You have to get in this code the values you need to work with, for example:
    var search_type = document.getElementsByName("tr")[0].value  //Get the value of the selected option ONE/TWO

    $.ajax({  //Call ajax function sending the option loaded
      url: "/search_ajax_function/",  //This is the url of the ajax view where you make the search 
      type: 'POST',
      data: "search_type="+search_type,
        success: function(response) {
            result = JSON.parse(response);  // Get the results sended from ajax to here
            if (result.error) { // If the function fails
                // Error
                alert(result.error_text);
            } else {  // Success
                for(var i=0;i < result.item_list.length;i++){
                    //Here do whatever you need with the results, like appending to a result div
                    $('#result_div').append(result.item_list[i]);                                                  
                } 
            }
        }
    });              
    }

You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.


AJAX function called by JQuery

Remember you need to add an url for this Ajax function in your urls.py something like: url(r'^/search_ajax_function/?$', 'your_project.ajax.search_ajax', name='search_ajax'),

Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson

@csrf_exempt
def search_ajax(request):    
    response = []
    if "search_type" in request.GET:
        search_type = request.GET['search_type']
    else:
        return HttpResponse(simplejson.dumps(response))

    #Now you have here Search_type and you can do something like
    books = Travel.objects.filter(froms__icontains=q)
    for item in books:
        response.append({'id': item.id, 'name': item.name})  # or whatever info you need
    return HttpResponse(simplejson.dumps(response))

So, without leaving the page you receive via javascript a list of books that contains the query your looking for. So in the first function, the javascript one, when you receive the response from AJAX, you have a list like:

[{'id':1, 'name':'book1'},{'id':2, 'name':'book2'},{'id':3, 'name':'book3'}]

So you can have a div like <div id="result_div style="display:none"></div> and when you receive the list, you make the div visible and append the result with the format or data you want


I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.

The basics for understanding is something like:

  1. JQuery function called on click or any event you need
  2. JQuery get some values on the template and send them to AJAX via POST
  3. Receive that information in AJAX via POST
  4. Do whatever you need in AJAX like a normal DJango view
  5. Convert your result to JSON and send back to the JQuery function
  6. JQuery function receive the results from AJAX and you can do whatever you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM