Django与Ajax和jQuery

I would like after clicking on one of the many Item shown a window with his description (single item description).

How to create this using Ajax and jQuery with Django?

model:

class Item(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    desc = models.TextField()

views:

def item_list(request):
    items = Item.objects.all()[:6]
    return render_to_response('items.html', {'items':items}, context_instance=RequestContext(request))


def single_item(request, slug):
    item = Item.objects.get(slug=slug)
    return render_to_response('single.html', {'item':item}, context_instance=RequestContext(request))

template:

<!-- Single item description: -->

<div id="description">
    <img src="/site_media/images/photo.png">
        <div id="item_description">
            <input name="add" type="button" id="add" value="Add to Cart">
                <p class="title">Single Item name</p>
                <p class="description"><span>Description:</span>
                    This is single item description
                </p>
            </div>
        </div>

<!-- All item: -->

            <div id="item">
                {% for i in items %}
                    <div class="item">
                    <img src="/{{ i.image.url }}"  />
                    <p>
                    <span> {{ i.name }} </span>
                    <span> {{i.price}} </span>
                    </p>
                    </div>
                {% endfor %}
            </div>
        </div>

    </div>

If you want to use ajax to refresh your page, you'll need to do three things:

  • Add an entry to urls.py for the ajax call (or add a condition to your view function to process the request if it's ajax)
  • Add the javascript block to make the ajax call and update the html/text with the new data
  • Add the code in your views.py to handle the ajax call and respond with json data

urls.py ...

url(r'/ajax-view-single/)/$', 'ajax_single_item', name='app_name_ajax_single_item'),

html/js

<script type="text/javascript" src="/js/json2.js"></script>
$("#view-single-item").click(function () {
        try {
            // get slug from html
            var slug = "";
            var data = {
                slug: slug
            };
            $.get('{% url app_name_ajax_single_item %}', data, function(data){

               // your data returned from django is in data
               alert(data.item_name);

            }, 'json');
            //$('#error').hide();
        }
        catch(err) {
            $('#error').html(err);
            $('#error').show();
        }
        return false;
    });

views.py

from django.http import HttpResponse
from django.utils import simplejson
from django.shortcuts import get_object_or_404

def ajax_single_item(request):
    '''gets single item'''
    if not request.is_ajax():
        return HttpResponse(simplejson.dumps({'result': False}))

    # get slug from data
    slug = request.GET.get('slug', None)

    # get item from slug
    item = get_object_or_404(Item, slug=slug)
    return HttpResponse(simplejson.dumps({
        'result': True,
        'item_name': item.name,
        'item_price': item.price,
        'item_desc': item.desc,
        'item_slug': item.slug
    }))