Pyramid framework tips: Form validation

For form validation in pyramid framework there is FormEncode package. FormEncode is a validation and form generation package. pyramid_simpleform is a add-on for pyramid framework and uses FormEncode.

SimpleForm in Pyramid Applications: install with easy_install:

$ easy_install pyramid_simpleform

In your controller code FormEncode Schema:

class CategoryForm(Schema):
  filter_extra_fields = True
  allow_extra_fields = True
  # category name not empty
  name = validators.String(not_empty=True)

 # edit function with form.validate()
 @view_config(route_name="category_edit", renderer="category/edit.html")
 def edit(request):
    """category edit """
    id = request.matchdict['id']
    dbsession = DBSession()
    category = dbsession.query(Category).filter_by(id=id).one()
    if category is None:
        request.session.flash("error;Category not found!")
        return HTTPFound(location=request.route_url("category_list"))        

    form = Form(request, schema=CategoryForm, obj=category)
    if "form_submitted" in request.POST and form.validate():
        request.session.flash("warning;The Category is saved!")
        return HTTPFound(location = request.route_url("category_list"))

    action_url = request.route_url("category_edit", id=id)
    return dict(form=FormRenderer(form),

See please full customers app code for template details.

Leave a Reply