Form Handling and Rendering for Pyramid

Scott Torborg - Cart Logic

Form rendering and validation for Pyramid. Doesn’t render HTML itself, so you have full control over form markup.

Heavily inspired by the pyramid_simpleform package, rewritten to work with WebHelpers2 and Python 3 and fix some issues with the original.

Contents

Quick Start

Install

Install with pip:

$ pip install pyramid_uniform

Use in a Pyramid App

No config.include() directive or setting modifications are required to use pyramid_uniform. Instead, two primary classes are used directly: Form and FormRenderer.

You can use Form alone to validate and process a form, with a FormEncode Schema.:

from formencode import Schema, validators
from pyramid_uniform import Form


class MySchema(Schema):
    name = validators.String()
    size = validators.Int()
    published = validators.Bool()


def myview(request):
    obj = ...

    # Initialize the form
    form = Form(request, MySchema)

    # Check for schema validity.
    if form.validate():

       # Update the attributes of obj based on validated form fields.
       form.bind(obj)

A common pattern is to use the same view (or handler action) to show a form and process the result. To do this, use a FormRenderer class to wrap the Form instance for presentation.:

from formencode import Schema
from pyramid_uniform import Form, FormRenderer


class MySchema(Schema):
    name = validators.String()
    size = validators.Int()
    published = validators.Bool()


def myview(request):
    obj = get_thing(request)

    # Initialize the form
    form = Form(request, MySchema)

    # Check for schema validity.
    if form.validate():

        # Update the attributes of obj based on validated form fields.
        form.bind(obj)
        return HTTPFound(...)

    # Form data is not present or not valid, so show the form.
    renderer = FormRenderer(form)
    return {'renderer': renderer, 'obj': obj}

To use renderer in a template, call methods on it to generate HTML form tags:

<h1>Edit ${obj}</h1>

${renderer.begin()}
  ${renderer.text('name', obj.name)}
  ${renderer.select('size', obj.size, range(10))}
  ${renderer.checkbox('published', checked=obj.published)}
${renderer.end()}

Extensive customization of the validation and rendering behavior is possible. For details, see the API documentation.

API Reference

class pyramid_uniform.Form(request, schema, method='POST')[source]
assert_valid(**kw)[source]
bind(obj)[source]
errors_for(field)[source]
is_error(field)[source]
method_allowed[source]

Is the method that was used to submit this form allowed?.

If this form doesn’t have a request method set (i.e., if it was explicitly set to None), any method is valid. Otherwise, the method of the form submission must match the method required by this form.

validate(skip_csrf=False, assert_valid=False)[source]

Validate a form submission.

When assert_valid is False (the default), a bool will be returned to indicate whether the form was valid. (Note: this isn’t strictly true–a missing or bad CSRF token will result in a immediate 400 Bad Request response).

When assert_valid is True, certain conditions will be assert``ed. When an assertion fails, the resulting ``AssertionError will cause an internal server error, which will in turn cause an error email to be sent out.

validate_csrf(params=None)[source]
exception pyramid_uniform.FormError(*args, **kw)[source]

Superclass for form-related errors.

exception pyramid_uniform.FormInvalid(*args, **kw)[source]

Raised when form data is used but the form is not valid.

message = 'Form is invalid'
exception pyramid_uniform.FormNotValidatedError(*args, **kw)[source]

Raised when form data is used before form has been validated: for example, when form.bind() is called.

message = 'Form has not been validated; call validate() first'
class pyramid_uniform.FormRenderer(form, csrf_field='_authentication_token', id_prefix=None)[source]
begin(url=None, **attrs)[source]
csrf(name=None)[source]
csrf_token(name=None)[source]
end()[source]
class pyramid_uniform.Renderer(data, errors, id_prefix=None)[source]
checkbox(name, value='1', checked=False, label=None, id=None, **attrs)[source]
errorlist(name)[source]
errors_for(name)[source]
file(name, value=None, id=None, **attrs)[source]
hidden(name, value=None, id=None, **attrs)[source]
is_error(name)[source]
password(name, value=None, id=None, **attrs)[source]
radio(name, value=None, checked=False, label=None, **attrs)[source]
select(name, selected_values, options, id=None, **attrs)[source]
submit(name, value=None, id=None, **attrs)[source]
text(name, value=None, id=None, **attrs)[source]
textarea(name, content='', id=None, **attrs)[source]
value(name, default=None)[source]
class pyramid_uniform.State(request)[source]

A relatively simple state object for FormEncode to use, with a reference to the request being validated.

Contributing

Patches and suggestions are strongly encouraged! GitHub pull requests are preferred, but other mechanisms of feedback are welcome.

pyramid_uniform has a comprehensive test suite with 100% line and branch coverage, as reported by the excellent coverage module. To run the tests, simply run in the top level of the repo:

$ tox

This will also ensure that the Sphinx documentation builds correctly, and that there are no PEP8 or Pyflakes warnings in the codebase.

Any pull requests should preserve all of these things.

Indices and Tables