python – WTForms:在发布时将表单值传递回用户
发布时间:2020-12-20 13:29:11 所属栏目:Python 来源:网络整理
导读:当GET和POST方法都在同一个处理程序类中时,我想在表单验证失败后用用户输入填充表单字段,我这样做…… Class CommentHandler(BaseHandler): def get(self,form=None): if form is None: # create new form unless populated form is passed in form = Commen
当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? 解决方法
当您发布并调用validate()时,WTForms将表单编码数据绑定到Form实例. http POST可以像GET一样返回响应,这就是为什么当服务器应用程序验证失败并且您尝试刷新时,您有时会在浏览器中获取这些有趣的消息.这是因为刷新操作将调用GET处理管道,您将丢失POST数据.
您需要做什么而不是委托回get实现,您只需要从post实现中呈现一个响应,该响应将Form实例与绑定到它的数据一起传递回响应中.如果您以建议的方式设置了模板,则数据将自动显示在相应的字段中.下面是您的处理程序可能看起来的片段. 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实例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |