Create custom URLs

URL structures are very important from SEO and usability point of view. With web2py, your app can automatically create custom URLs using compute function and IS_SLUG validator .

Model db_tables.py


Define your table in models. Note, keep_underscore is False by default.





























db.define_table('my_page',

Field('name', 'string', length=256, label=T('Name')),
Field('title', 'string', length=512, label=T('Title')),
Field('subtitle', 'string', length=512, label=T('Subtitle')),
Field('page_content', 'text', label=T('Page Content')),
Field('parent', 'reference my_page', label=T('Parent')),
Field('url_builder', unique=False,readable=True, writable=True, length=255, label=T('Url Builder')),
Field('url', unique=True, length=255, readable=True, writable=True, label=T('Url')),
Field('approved', 'boolean', default=True, label=T('Approved')),
format='%(name)s')
db.my_page.url_builder.compute = lambda r: str(r.name)+' '+str(r.title)
db.my_page.parent.requires = IS_EMPTY_OR(IS_IN_DB(db, db.my_page.id, ' %(name)s - %(title)s - ID %(parent)s',
orderby=db.my_page.parent))
db.my_page.url.compute = lambda row: IS_SLUG(keep_underscores=False)(row.url_builder)[0]


## Below code is needed only once.
if db(db.my_page.id > 0).count() == 0:
db.my_page.insert(
name = 'index',
title = 'index',
subtitle = 'index',
page_content = 'Lore ipsum lore ipsum Lore ipsum lore ipsum')
db.my_page.insert(
name = 'Second Page',
title = 'My home page',
subtitle = 'index',
page_content = 'Lore ipsum lore ipsum Lore ipsum lore ipsum')

Controller page.py


page.py controller takes an argument (request.args(0)) and checks if args is a digit and if it's in a database.























def index():

redirect(URL('page','show_page',args='index'))

def show_page():
if not len(request.args):
## You will need to create a record 'index' in 'url' field
redirect(URL('page', 'show_page',args='index')) ## You will need to create a record with 'url' record 'index'
else:
if request.args(0) and request.args(0).isdigit():
page = db.my_page(request.args(0))
if not page:
raise HTTP(404)
else:
redirect(URL('page', 'show_page',args=page.url))
else:
page = db(db.my_page.url==request.args(0)).select().first()
if not page:
raise HTTP(404)
elif page.approved==False:
session.flash='Sorry page is not published or apporved'
raise404 = True
raise
HTTP(404)
return dict(page=page)

View page/show_page.html


Full URL is http:127.0.0.1/appname/page/show_page/1 will be redirected to http:127.0.0.1/appname/page/show_page/index









{{extend 'layout.html'}}


{{block header}}
<div class="page-header">
<h1 class="blog-title"> {{=page.name}} </h1>
</div>
{{end}}

{{=page.page_content}}

html layout.html


You will need to add following block codes to your layout.html.





{{block header}}
{{end}}

Result

IS_SLUG

loading...

Comments

loading...

Tag Cloud

accepted Acces Control access rights actions_disabled admin album allowed_attributes allowed_schemes App apps args auth authentication B bar chart BEAUTIFY begin BODY BR carousel CAT CENTER chart check CLEANUP client request client_side CMS CODE COL COLGROUP comment compute contact form crud.create crud.delete crud.read crud.select crud.tables CRUD custom attributes custom form DAL data define_table deletable depriciated DIV doctype dot dspval EM embed64 enable_record_version end error_message example extension Field types Field FIELDSET file filename form.accepted form.accepts form.process form.validate FORM format Forms gallery Grid H1 H2 H3 H4 H5 H6 hash_vars Hello helper helpers highchart hmac_key host hosting HTML image images inpval ip address ip IS_DATETIME IS_DATETIME_IN_RANGE IS_DECIMAL_IN_RANGE IS_EMPTY_OR IS_EQUAL_TO IS_EXPR IS_FLOAT_IN_RANGE IS_IMAGE IS_INT_IN_RANGE IS_IN_DB IS_IN_SET IS_IPV4 IS_LIST_OF IS_NOT_EMPTY IS_NOT_IN_DB IS_NULL_OR is_slug IS_STRONG IS_TIME IS_UPLOAD_FILENAME IS_UPPER IS_URL lable lambda lang lastdot linkto li_class li_first li_last login_methods maximum maxip maxlen MENU min minimum minip mobile mode module multiple permitted_tags pie chart placeholder plugin prepend_scheme pythonanywhere query rating reCaptcha redirect request.now routes.py salt sanitize scheme services settings slug sortable special SQLFORM() SQLFORM.grid SQLFORM SSL submit table constructor TAG test text TinyWebsite ul_class update upper URL rewrite URL validator value vars Views widget XML xmlescape _class _common_fields


Powered by
Web2py

Hosted on
www.pythonanywhere.com
(affiliated link)