Created
October 9, 2012 14:32
-
-
Save johnschimmel/3859214 to your computer and use it in GitHub Desktop.
Sample flask route for form display and form validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this is our main page | |
@app.route("/", methods=['GET','POST']) | |
def index(): | |
# get Idea form from models.py | |
idea_form = models.IdeaForm(request.form) | |
# if form was submitted and it is valid... | |
if request.method == "POST" and idea_form.validate(): | |
# get form data - create new idea | |
idea = models.Idea() | |
idea.creator = request.form.get('creator','anonymous') | |
idea.title = request.form.get('title','no title') | |
idea.slug = slugify(idea.title + " " + idea.creator) | |
idea.idea = request.form.get('idea','') | |
idea.categories = request.form.getlist('categories') # getlist will pull multiple items 'categories' into a list | |
idea.save() # save it | |
# redirect to the new idea page | |
return redirect('/ideas/%s' % idea.slug) | |
else: | |
# for form management, checkboxes are weird (in wtforms) | |
# prepare checklist items for form | |
# you'll need to take the form checkboxes submitted | |
# and idea_form.categories list needs to be populated. | |
if request.method=="POST" and request.form.getlist('categories'): | |
for c in request.form.getlist('categories'): | |
idea_form.categories.append_entry(c) | |
# render the template | |
templateData = { | |
'ideas' : models.Idea.objects(), | |
'categories' : categories, | |
'form' : idea_form | |
} | |
return render_template("main.html", **templateData) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you know how to do the exact same thing, retrieve the categories submitted on the form and append it but using flask-wtf?
I'm trying to do it but I can't figure it out!