Search code examples
pythondatabaseweb2py

Saving author of form Web2Py


How can I save & display the name of the user who submits a form saved in a database.

For example:

I have a form that allows users to review products. I then have a table that lists these reviews. On the table I want to list each users name besides each review.


Solution

  • You could add a reference field pointing to the db.auth_user table (or whatever table in which you store user data):

    db.define_table('review',
        ...,
        Field('reviewer', 'reference auth_user', default=auth.user_id, writable=False),
        ...)
    

    With the above code, the default value for the "reviewer" field is the ID of the currently logged in user. The field is not writable, so the user has no way to change that (in the review entry form, you might also want to set its readable attribute to False, as there is no need for the author to see it).

    Then to display the reviewer name along with the review, you could either do a join or use a recursive select (the former is more efficient if you are displaying many reviews at once, as the recursive select approach requires a separate database query to get each review's author).