Search code examples
pythonweb2py

Using web2py's grid/smartgrid what is the best way to limit editing and deleting to only the user that made the post


Here is the index, very simple.

def index():
grid = SQLFORM.smartgrid(db.image, linked_tables=['image'])
return dict(grid=grid)

Here is the model, I'm using the basic auth package:

db = DAL("sqlite://storage.sqlite")
import datetime
from gluon.tools import Auth
auth = Auth(db)
auth.define_tables(username=False, signature=False)

auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True


db.define_table('image',
            Field('user_id', 'reference auth_user', default=auth.user_id),
            Field('post_subject'),
            Field('post_content', 'text'),
            Field('created_on', 'datetime', default=datetime.datetime.utcnow()),
            Field('updated_on', 'datetime', update=datetime.datetime.utcnow()),
            )


db.define_table('post',
            Field('image_id', 'reference image'),
            Field('author'),
            Field('email'),
            Field('body', 'text'))



db.image.user_id.readable = db.image.user_id.writable = False

db.image.post_subject.requires = IS_NOT_EMPTY()
db.image.post_content.requires = IS_NOT_EMPTY()

db.image.created_on.writable = False
db.image.updated_on.writable = False

I've trying following the instructions from the book, which says to do this:

grid = SQLFORM.grid(db.auth_user,
     editable = auth.has_permission('edit','auth_user'),
     deletable = auth.has_permission('delete','auth_user'))

However, it doesn't work, it just makes it so no one can edit anything

Thanks.


Solution

  • auth.has_permission is only useful if you set the permissions somewhere, which it appears you have not done. Instead, though, you should pass functions via the editable and deletable arguments -- the function will receive a row in the table and should return True if the current user is allowed to edit the row:

    SQLFORM.grid(..., editable=lambda r: r.user_id == auth.user_id)
    

    From the documentation:

    deletable, editable and details are usually boolean values but they can be functions which take the row object and decide whether to display the corresponding button or not.