Skip to content

Instantly share code, notes, and snippets.

@prokoptsev
Last active August 29, 2015 14:23
Show Gist options
  • Save prokoptsev/08929cf807be18be30a4 to your computer and use it in GitHub Desktop.
Save prokoptsev/08929cf807be18be30a4 to your computer and use it in GitHub Desktop.
# source: https://groups.google.com/forum/#!topic/wtforms/ur84vD5S66Y
# Not exactly, but there are multiple ways to do this in WTForms that
# are different, each with its own advantages.
# Old Method: For two completely different forms which you want to
# validate entirely separately, you can create two form instances, each
# with their own prefix. This was the only way prior to WTForms 0.4 or
# thereabouts, to run multiple forms.
def login_register_view(request):
reg_form = RegisterForm(request.POST, prefix='register')
login_form = LoginForm(request.POST, prefix='login')
# This creates fields named like register-username, login-username, and
# the like. You also get fine-grained control over validating each form
# separately (perhaps, in response to a SubmitField or the like)
# Now, an even more powerful solution, which provides basically
# everything that django's FormSet provides, is to use FormField and
# FieldList. This can be done for a master-detail record validated
# together, or a master record with multiple sub-records wherein you can
# control how many sub-lists exist.
class ArticleEdit(Form):
# forms containing enclosures may contain bare fields, but aren't
# required to
title = TextField()
# a related child object editing. form.summary['foo'] or
# form.summary.form.foo can access the fields of ArticleSummaryForm.
summary = FormField(ArticleSummaryForm)
# The most powerful enclosure type. This combines FieldList
# with FormField to create a multiple-edit scenario.
pages = FieldList(FormField(ArticlePageForm), min_entries=1, max_entries=10)
# There are some examples of how to use FieldList on the documentation;
# and with the appropriate view logic, you can create a number of
# powerful forms, such as multiple-edit-inline with individual
# validation as required. With all enclosures, validating the outermost
# enclosure will call validate() on any enclosed fields and forms.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment