close Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Version 4 (modified by cmlenz, 16 years ago) (diff)

--

Form Processing

Diva comes with a simple module supporting the processing of HTML forms. A request handler that does some simple form processing typically looks something like this:

from diva.forms import Form, TextValidator
from diva.routing import redirect_to
from diva.templating import output, render

class LinkForm(Form):
    username = TextValidator(required=True)
    url = TextValidator(required=True)
    title = TextValidator(required=True)

@output('submit.html')
def submit(request, response):
    form = LinkForm()
    if request.method == 'POST':
        if 'cancel' in request.POST:
            redirect_to('index')
        if form.validate(request.POST):
            # Form is valid, store data int the database
            link = Link(**form.data)
            link.store(app.db)
            redirect_to('info', link.id)
    return render(errors=form.errors)

This simple example already does a couple of things you may not expect:

  • When the form is redisplayed on POST due to validation errors, the form elements will already be populated with the previously entered values.
  • The form submission is protected against Cross-Site Request Forgery (CSRF) attacks, by adding a form token both as a cookie, and as a hidden form input field.

API Documentation

Error: Macro PythonDoc(trunk, diva.forms) failed
Unsupported version control system "svn": No module named svn