e-Jah
e-Jah

Reputation: 335

How I am doing Ajax with Django now: looking for advices/comments

I would like share with you how I am doing my Ajax stuff with Django for the moment. I would like have your advices/comments to see if I am doing it right.

I will of course oversimplified the code, just to show the process.

Here is my template code:

<!-- I store the full url to access object details so I can use url feature.
If I just store the pk, I would have to hardcode the url to fetch the object
detail later. Isn't it? -->
<ul>
{% for item in items %}
    <li url="{% url project.item.views.details item.pk %}">{{ item.name }}</li>
{% endfor %}
<ul>

<div id="details"></div>


<script> 
$("li").click(function(elmt){
    // I just reuse the url attribute from the element clicked
    var url = $(elmt.currentTarget).attr('url');
    $.getJSON(url, function(data) {
        if (data.success) {
            $("#details").html(data.html);
        } else {
            $("#details").html("Something went wrong");
        }
    });
});
</script>

Here is the code I use in my view:

def details(request, item_id):
    item = Items.objects.get(pk=item_id)
    # Just render a view with the details, and return the view
    html = render_to_string("items/_details.html", {'item': item})
    return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")

What do you think about my way to do that?

Thank you in advance for your help!

Upvotes: 3

Views: 217

Answers (2)

sunn0
sunn0

Reputation: 3046

Nothing wrong with the Django code but you may want it to work for non javascript clients as well and use valid HTML:

<ul>
{% for item in items %}
    <li><a href="{{ item.get_absolute_url }}">{{ item.name }}</a></li>
{% endfor %}
<ul>

$("a").click(function(){
    // I just reuse the url attribute from the element clicked
    // li does not have an url attribute
    var url = $(this).attr('href');
    $.getJSON(url, function(data) {
        if (data.success) {
            $("#details").html(data.html);
        } else {
            $("#details").html("Something went wrong");
        }
    });
    return false;
});

def details(request, item_id):
    item = Items.objects.get(pk=item_id)
    # Just render a view with the details, and return the view
    if request.is_ajax():
        html = render_to_string("items/_details.html", {'item': item})
        return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")
    else:
        #non ajax request rendering complete html
        return render_to_response("items/detail.html", {'item': item})

Upvotes: 2

Scott
Scott

Reputation: 1477

I personally prefer using middleware to host web services since they allow you to not load Django in its entirety, but still access what you need to.

Still, using views for web services is certainly valid and works.

Upvotes: 0

Related Questions