Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django star rating system and AJAX

I am trying to implement a star rating system on a Django site.

Storing the ratings in my models is sorted, as is displaying the score on the page. But I want the user's to be able to rate a page (from 1 to 5 essentially) without a refresh or change of page.

I have found the following, and like the style of the stars here: http://jvance.com/blog/2008/09/22/JQueryRaterPluginNew.xhtml

Currently have a limited understanding of javascript and AJAX. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating?

It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. It is stored in the models whether they have already voted and what their previous vote was. But how would I be able to modify the stars to show this?


So if you know how to do these things, or a more appropriate star rating graphics solution, or any good tutorials... please do share. Thank you.

like image 549
Jon Cox Avatar asked Feb 12 '11 19:02

Jon Cox


1 Answers

AJAX sounds scary and confusing but it doesn't have to be. Essentially what you want to do is post some data to a particular url/view combo. See jQuery.post for more information on using AJAX to send data to the server.

#urls
urlpatterns += patterns('',
url(r'^article/rate/', 'article.rate'),

#views 
def rate(request):
    if request.method == 'POST':
       # use post data to complete the rating..

#javascript
$.post("/article/rate", { rating: 3, article: 2 },
    function(data) {
       // success! so now set the UI star to 3
});

As far as I know, star-ratings are produced with radio controls and css. So if you want to show the current rating per user on load of the page, just have your template render the associated radio with the checked option.

like image 121
Josh Smeaton Avatar answered Sep 19 '22 08:09

Josh Smeaton