How do I POST an object's model for use in a view via ajax?
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 }}", 开发者_如何学Go// 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 ...
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
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/
精彩评论