4. Configure db1.py
- You could place your additional models in
db.py
, but I prefer to place non-system table definitions in their own db file. So we need to create a new file called db1.py
. Under Models, click the "Create" button.
- Inside of
db1.py
we define a table called the_aliaser
with five fields; name
, description
, the_url
, the_slug
, alias_url
.
##### Copy the code below and paste into db1.py #####
db.define_table('the_aliaser',
Field('name',
type='string',
label=T('Name')),
Field('description',
type='text',
label=T('Description')),
Field('the_url',
type='string',
label=T('The URL')),
Field('the_slug',
unique=True,
type='string',
label=T('Slug Name')),
Field('alias_url',
type='string',
label=T('Alias URL'))
)
- More on the table constructor
- We can then add validators to the table.
- On line 22 we apply the
IS_SLUG()
validator which enforces rules for slugs including making sure that underscores are converted to dashes. - On line 23 we apply the validator
IS_NOT_IN_DB()
to the name table to make sure no duplicate names are entered. - On line 24 we have a computed field which concatenates the URL of the
resolve_alias
function with the slug that is generated. We will explain how this works in a future section. - These validators must appear after the table definition.
- It is also important to note that the
alias_url.compute
must come after the_slug.compute
.
##### Copy the code below and paste into db1.py below the table definition #####
db.the_aliaser.the_slug.compute = lambda row: IS_SLUG(keep_underscores=False)(row.name)[0]
db.the_aliaser.name.requires = IS_NOT_IN_DB(db, db.the_aliaser.name)
db.the_aliaser.alias_url.compute = lambda row: request.env.http_host + '/aliaser/default/resolve_alias/' + row.the_slug
[ Previous ] [ Next ]