WTForms:在帖子上将表单值传递回用户

时间:2012-07-23 10:38:26

标签: python webapp2 wtforms

当GET和POST方法都在同一个处理程序类中时,我想在表单验证失败后使用用户输入填充表单字段,我这样做......

Class CommentHandler(BaseHandler):
    def get(self, form=None):
        if form is None: # create new form unless populated form is passed in
            form = CommentForm()
        # query DB and create template context
        self.render('page.html', **context)

    def post(self):
        form = CommentForm(self.request.POST)
        if form.validate():
            # populate entity with form data and save to DB
            return self.redirect_to('page')
        self.get(form=form) # pass populated form back to user for editing

我不知道这是否是将表单数据恢复给用户的最佳方式,但它似乎有效。我的问题是:如果GET和POST方法在不同的处理程序类中,如何将这些数据传回表单?

class PageHandler(BaseHandler):
    def get(self):
        # displays form to user

class CommentHandler(BaseHandler):
    def post(self):
        # processes POSTed form data...
        # but if form.validate() fails,
        # how can I pass the form data back to the user
        # so they can edit their form input?

2 个答案:

答案 0 :(得分:1)

当您post并致电validate()时,WTForms会将表单编码数据绑定到Form实例。 http POST可以像GET一样返回响应,这就是为什么当服务器应用程序验证失败并且您尝试刷新时,有时会在浏览器中收到这些有趣的消息。这是因为刷新操作将调用GET处理管道,您将丢失POST数据。

您需要做什么而不是委托回get实现,只需要从post实现中提交响应,该实现将Form实例与绑定的数据一起传回在回应中。如果您以建议的方式设置了模板,则数据将自动显示在相应的字段中。以下是Handler可能显示的内容的摘要。

def post(self):

    form = CommentForm(self.request.POST)

    if form.validate():
        # populate entity with form data and save to DB
        return self.redirect_to('page')

    # If we are here it means we failed validation
    # We need to send back the data the use supplied 
    # with error messages so we can re-render the form
    # with their data and error messages indicating why
    # it was rejected.

    self.render('page.html', form=form) # pass populated form back to user for editing

这当然假设您的page.html知道如何处理Form实例。

答案 1 :(得分:0)

这是一个可以帮助您解决问题的工作流程。我选择提供工作流而不是特定的代码段,以避免在用于解决问题的技术中过于规范。

GET
if session contains form data:
  add form data from session to template context
display form

POST
if form validates:
  clear this form data from session
  save to db
else:
  save form data to session
  redirect to GET handler