Skip to content

Instantly share code, notes, and snippets.

@mdipierro
Created July 16, 2015 09:15
Show Gist options
  • Save mdipierro/f95dab0f869f5504482e to your computer and use it in GitHub Desktop.
Save mdipierro/f95dab0f869f5504482e to your computer and use it in GitHub Desktop.
contact form in web2py
# append to scaffoling models/db.py
db.define_table('contact',
Field('your_name',requires=IS_NOT_EMPTY()),
Field('email',requires=IS_EMAIL()),
Field('message','text'))
# append to scaffolding controllers/default.py
def contact_us():
form = SQLFORM(db.contact)
if form.process().accepted:
mail.send(to='[email protected]',
subject='contact request from %(your_name)s %(email)s' % form.vars,
message = form.vars.message)
session.flash = 'Thank you, your form was submitted'
redirect(URL('index'))
return dict(form=form)
# views/default/contact_us.html
{{extend 'layout.html'}}
{{=form}}
Configure the email in private/appconfig.ini. The database table will be create automatically. Runs on VPS and Google App Engine, with any SQL engine, MongoDB, and Google Datastore. Uses bootstrap 3 by default.
@andyhasit
Copy link

Here's a suggested revision with following changes

  1. Renamed field "message" as that is a reserved keyword in some dbs (must remember to change form.vars.message to form.vars.form_message in the call to send or it will be null and you get a nasty error, in 2.14.6 at least)
  2. Checks if email actually sent, as otherwise the notification is erroneous.
  3. Added reply_to, which helps.
  4. Changed to use modern string formatting, just because.
  5. Changed to not use flash message unless there's an error, because I think its nicer, but you may disagree :-)

db.define_table('contact',
Field('your_name',requires=IS_NOT_EMPTY()),
Field('email',requires=IS_EMAIL()),
Field('form_message','text', label='Message'))

append to scaffolding controllers/default.py

def contact_us():
form = SQLFORM(db.contact_form)
sent = False
if form.process().accepted:
sent = mail.send(to='[email protected]',
subject='auto-contact {name} {email}'.format(**form.vars),
reply_to=form.vars.email,
message=form.vars.form_message
)
if not sent:
session.flash = 'Error sending message, please use email.'
return dict(form=form, sent=sent)

views/default/contact_us.html

{{extend 'layout.html'}}
{{if sent:}}

Form submitted, thank you.

{{else:}} {{=form}} {{pass}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment