Poorva Rane Poorva Rane - 4 months ago 11x
Ajax Question

Get POST value from select tag in Django 1.7

In my forms.py I have

class CollegeForm(forms.ModelForm):
collegeName = forms.ModelChoiceField(label='Select College', queryset=College.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))

class Meta:
model = College
fields = ('collegeName',)

In my views.py,

if(request.method =='POST'):
college_form = CollegeForm(request.POST)
college_form = CollegeForm()
return render(request, 'market/product_list.html',{'college_form': college_form})

In my product_list.html file, I have

<div class="col-md-4">
{{ college_form.as_p }}

I want to dynamically update the content of the page based on what the user selects from the drop down list. Is there a way to do so by making an Ajax call? If yes, how?


The short answer is yes. But it very much depends on what it is that you are trying to do.

  1. Depending on how much of your page you want to change and in what way...you may not need an ajax call..you could send down the data in the initial request and use javascript to update the page in specific ways.

  2. If you have a lot of data for each selection then you could take a very simple route of doing a page load each time a new selection is made. (the user experience here is a bit clunky, but it can be effective).

  3. Finally, if you have a lot of data and want the slick experience you can use ajax. You will need to have an endpoint to provide you with the necessary data depending on the selection. If you go this route I recommend using some javascript framework like jquery. Here is the documentation on the ajax call.

Here is an example of what an ajax solution might look like. This is just a general outline and assuming you are using jquery. There are extra details that will depend on implementation specifics:

Your new views.py:

import json

from django.shortcuts import render
from django.http import HttpResponse

from forms import CollegeForm
from models import CollegeInfo

def original_endpoint(request):
    # ...
    if request.method == 'POST':
        college_form = CollegeForm(request.POST)
        college_form = CollegeForm()
    return render(request, 'market/product_list.html', {'college_form': college_form})

def college_data_endpoint(request, college_name):
    Endpoint for sending back college-specific data

    Response sent back in json format to make for easier processing with javascript

    # Get college-specific data from the db
    college = CollegeInfo.objects.get(id=college_name)

    # format it
    response_data = {
        'field1': college.field1,
        'field2': college.field2

    return HttpResponse(json.dumps(response_data), content_type='application/json')

Changes to product_list.html:

<div id="js-college-selector" class="col-md-4">
    {{ college_form.as_p }}

<div id="js-college-data" class="hidden">
    {# HTML form to fill in college info and possibly unhide #}

<script type="text/javascript">
    // Assuming that you are using jquery
    // You would eventually want to move this to a javascript file
    $("#js-college-selector").change(function() {
        // jQuery
        var selectedText = $(this).find(':selected').text();
            type: "GET", //rest Type
            dataType: 'jsonp', //mispelled
            url: "path/to/college/info/endpoint",
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function (data, textStatus, jqXHR) {
                // data is the college info to be used to modify the page with