I would like to share with you how I am doing my Ajax stuff with Django at the moment. I would like to receive your advice / comments to make sure that I am doing it right.
Of course, I would simplify the code just to show the process.
Here is my template code:
<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){
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 that I use in my view:
def details(request, item_id):
item = Items.objects.get(pk=item_id)
html = render_to_string("items/_details.html", {'item': item})
return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")
What do you think of my way of doing this?
Thank you in advance for your help!
source
share