Working on this recently, so thought I would provide a solution to the mix. Firstly, I'm using RateIt, which I have found to be very simple to set up and quite intuitve to use (add the RateIt *.js
and .*css
files to your base.html
template):
http://www.radioactivethinking.com/rateit/example/example.htm
Here are the key pieces to my solution:
urls.py
url(r'^object/rate/$', RateMyObjectView.as_view(), name='rate_my_object_view'),
my_template.html
<div class="rateit" data-rateit-resetable="false">Rate it!</div>
ajax.js
$('.rateit').bind('click', function(e) {
e.preventDefault();
var ri = $(this);
var value = ri.rateit('value');
var object_id = ri.data('object_id');
$.ajax({
url: '/object/rate/?xhr',
data: {
object_id: object_id,
value: value
},
type: 'post',
success: function(data, response) {
console.log("ajax call succeeded!");
},
error: function(data, response) {
console.log("ajax call failed!");
}
});
});
Some view bits are from James Bennett (setting xhr
, for example):
http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/
views.py
from django.views.generic.base import View
from .models import MyObject
class RateMyObjectView(View):
def post(self, request):
my_object = MyObject.objects.all().last()
xhr = 'xhr' in request.GET
star_value = request.POST.get('value', '')
my_object.score = star_value
my_object.save()
response_data = {
'message': 'value of star rating:',
'value': star_value
}
if xhr and star_value:
response_data.update({'success': True})
else:
response_data.update({'success': False})
if xhr:
return HttpResponse(json.dumps(response_data), content_type="application/json")
return render_to_response(self.template_name, response_data)
models.py
from django.db import models
class MyObject(models.Model)
score = models.FloatField(max_length=1, default=0)
Keep in mind that this is a naive solution, and simply replaces the current star score in the last item in your object list. It's not ideal, as it would be better to store scores as their own model and link to the object. This was you can store them and do calculations like average, etc. I'm working on this now and will update this answer when I'm finished.