Skip to content

Instantly share code, notes, and snippets.

@johnschimmel
Created October 9, 2012 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnschimmel/3859214 to your computer and use it in GitHub Desktop.
Save johnschimmel/3859214 to your computer and use it in GitHub Desktop.
Sample flask route for form display and form validation
# 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)
@vititu
Copy link

vititu commented Mar 2, 2016

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!

@RareWarrior1
Copy link

salamat sa helmet heroes mga tanga

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment