views:

85

answers:

2

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 ...

+1  A: 

You could probably create a custom filter (django docs).

Current Code Attempt (Community Wiki):

from django import template

register = template.Library()

@register.filter
def app_label(value):
    """Return an object's app_label"""
    try:
        return value._meta.app_label
    except:
        pass

@register.filter
def object_name(value):
    """Return an object's object_name"""
    try:
        return value._meta.object_name
    except:
        pass

Then in your template:

{% load ... %}

{{ object|app_label }}
{{ object|object_name }}

The only other way I can think of would be adding a property to the model. This way means you don't have to modify the model

michael
I hadn't thought of that - thanks. Is a good idea. I just need to see how to turn around and take the text representation of the model and retrieve an actual object ... but I know the answer is out there.
thornomad
Cheers, as vikingosegundo mentioned the app name is probaly useful.... I didn't add error checking either. I've made this post community wiki so you can refine if you like
michael
I added the code I have working, with `try/except` in there (albeit, not very clever).
thornomad
+1  A: 

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/

vikingosegundo
That will be the perfect combination, I think! I am going to use a filter, because it seems to work and is pretty simple. Using get_model in my ajax view will do just what I need. Thanks.
thornomad