Friday, January 13, 2012

web2py: plugin rating widget

I was looking for a plugin for rating with starts and found this one but it doesn't give me much information how to do it so I gave up. (It's sad, I couldn't plug the plugin.)

Plugin Rating
http://www.web2py.com/plugins/default/rating

Now, kenji (s-cubism) just introduced the new plugin and it works like a charm ! It's easy to use and I strongly recommend if you're looking for the plugin.

Rating Widget
http://dev.s-cubism.com/plugin_rating_widget 

Here's how I did.

1. Create new app called "rating"

2. Create models/rating.py
# coding: utf8
from plugin_rating_widget import RatingWidget
db.define_table('product',
    Field('rating', 'integer',
          requires=IS_IN_SET(range(1,6)), # "requires" is necessary for the rating widget
))
################################ The core ######################################
# Inject the horizontal radio widget
db.product.rating.widget = RatingWidget()
################################################################################

3.  Edit controllers/default.py for def index

def index():
    form = SQLFORM(db.product)
    if form.accepts(request.vars, session):
        session.flash = 'submitted %s' % form.vars
        redirect(URL('index'))
    return dict(form=form)
4. Edit views/default.html

{{left_sidebar_enabled,right_sidebar_enabled=False,True}}
{{extend 'layout.html'}}
{{=form}}
5. Result

Of course, you can create another table and store the submitted value to it, calculate the average, whatever you like. This plugin is good enough for me to build some kind of user review app !