The web2py book gives an example of modelling an image blog. The lines of code relevant to my question are:
db.define_table('image',
Field('title', unique=True),
Field('file', 'upload'),
format = '%(title)s')
db.image.title.requires = IS_NOT_IN_DB(db, db.image.title)
The text states that expressions like db.image.title.requires are validators. But
- It does not make it clear whether
unique=Truein the expresssionField('title', unique=True)is also a validator with the exact same functionality - What impact a validator has on database-driven form generation.
From the book:
unique=Truedoes not result in a validator being created. It results in aUNIQUEconstraint being added to the database schema when web2py first creates the table in the database (assuming you have enabled migrations). If you call the DAL.insert()or.update()methods with values that would violate this constraint, the database will throw an error (which will result in a Python exception in your app).Setting
requires=IS_NOT_IN_DB(...)creates a validator, which will be run when you (a) submit a form created usingSQLFORMor (b) call the DAL.validate_and_insert()or.validate_and_update()methods. If validation fails, the insert/update is not sent to the database at all, and you do not get a Python exception, but simply a record of the failure (which is typically displayed on the form in the case of a form submission).If you will be making inserts and updates via forms, it is a good idea to use the validator, because it provides the proper user experience (i.e., displaying an error message with the form). It is also a good idea to set
unique=Trueso the database has the appropriate schema, in case you make inserts/updates via means other than forms (and possibly even outside of web2py or the DAL).