Jquery – How to POST an object’s model for use in a view via ajax

ajaxdjangojquery

Am working on my earlier hit count question and ran into another stumbling block: how do I post an object's model information through ajax ?

I am using the generic object_detail view for a number of my models and I want to add some ajax to the template that calls my updapte_object_hit_count function (thereby tracking the object's hit count).

But since the data is passed via json/ajax, I'm not sure how I figure out which model/object I am working with exactly.

For example, what I would like to do (jQuery):

$(document).ready(function() {

    var data = {
        model : "{{ object.model }}", // this doesn't work, obviously
        pk    : "{{ object.pk }}",
        };

    $.post('{% url update_object_hit_count %}',data);

});

In my view, something clever like:

def update_object_hit_count(request):
    post = request.POST.copy() 
    model = post['model']
    obj = model.objects.get(pk=post['pk'])
    # more stuff using this obj

Any ideas on how to accomplish this? I thought I may be able to use ContentType but not sure how …

Best Answer

Use a custom filter like described by michael and use django.db.model.get_model to retrieve a objects my provideing app name and model name

To retrieve both informations at once, a custom tag might be more useful than a filter

more informations about get_model in this article: http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/