Flask - WTForms - 两条路线,需要两次调用表格吗?
Flask - WTForms - two routes, need to call form twice?
- 我有一个显示带有表单的页面的路由。
- 当我提交表单时,它会调用另一个路由,我在其中处理表单
- 此路由然后重定向到上一个路由并显示初始页面
我的问题是:我需要在两条路线上都调用表单是否正确?
@route('/')
def home():
form = MyForm()
return render_template('index.html', form = form)
@route('/process_form')
form = MyForm()
if form.validate_on_submit():
# process form data here
return redirect(url_for('home')
你们会怎么做?我也可以将表单提交到同一个页面并在那里进行表单处理,但它可能会变得混乱,因为我最终会在页面上有多个表单,并有多个处理路径。
谢谢
D.
- 表单提交很可能会在 POST 中发送,而不是 GET。
- 如果网页有多个表单,每个表单都可能有自己的模型(即 Class)和表单实例。因此不应该有 'messy' 。
- 乱的不是表单,不是路由,而是为什么一个网页一个地方有这么多表单?
就我个人而言,我发现将 GET 和 POST 请求都放在一个路由下会更简洁:
@route('/', methods=['GET', 'POST'])
def home():
comment_form = CommentForm()
subscription_form = SubscriptionForm()
if subscription_form.validate_on_submit():
# process subscription form
redirect(url_for('home')
if comment_form.validate_on_submit():
# process comment form
redirect(url_for('home')
return render_template('index.html', subscription_form=subscription_form, comment_form=comment_form)
- 我有一个显示带有表单的页面的路由。
- 当我提交表单时,它会调用另一个路由,我在其中处理表单
- 此路由然后重定向到上一个路由并显示初始页面
我的问题是:我需要在两条路线上都调用表单是否正确?
@route('/')
def home():
form = MyForm()
return render_template('index.html', form = form)
@route('/process_form')
form = MyForm()
if form.validate_on_submit():
# process form data here
return redirect(url_for('home')
你们会怎么做?我也可以将表单提交到同一个页面并在那里进行表单处理,但它可能会变得混乱,因为我最终会在页面上有多个表单,并有多个处理路径。
谢谢 D.
- 表单提交很可能会在 POST 中发送,而不是 GET。
- 如果网页有多个表单,每个表单都可能有自己的模型(即 Class)和表单实例。因此不应该有 'messy' 。
- 乱的不是表单,不是路由,而是为什么一个网页一个地方有这么多表单?
就我个人而言,我发现将 GET 和 POST 请求都放在一个路由下会更简洁:
@route('/', methods=['GET', 'POST'])
def home():
comment_form = CommentForm()
subscription_form = SubscriptionForm()
if subscription_form.validate_on_submit():
# process subscription form
redirect(url_for('home')
if comment_form.validate_on_submit():
# process comment form
redirect(url_for('home')
return render_template('index.html', subscription_form=subscription_form, comment_form=comment_form)