我使用金字塔作为我的框架来处理项目。由于我曾经做过很多.ASP,每当用户提供无效输入时,我只能将文本分配给标签(通过" runat"属性然后只是简单地在后端分配消息)向用户发出信号,表明他们输入的信息无效而不删除所有输入的数据。在python中有相同的方法吗?最终,我希望能够做的是向用户报告他们的数据是否有效(我可以将他们重定向到同一页面),但是,我更喜欢不必刷新屏幕和让用户第二次填写表格(或由于错误而填写n个时间)。
答案 0 :(得分:1)
在概念层面,在传统的" (非AJAX)场景,每次用户点击提交时,您都会重新呈现表单,但根本没办法。您的ASP应用程序可能在幕后做同样的事情。如果出现错误,诀窍就是用用户已输入的数据重新呈现表单。
通常它看起来像这样(假设您没有使用任何表单库并手动编写表单)
@view_config(...., renderer='myform.mak')
def my_view(context, request):
if request.method == 'GET':
# display an empty form to the user
return {
'page_title': 'Please fill out this boring form',
'errors': {},
'data': {},
}
elif request.method == 'POST':
# an imaginary method which validates the data submitted by the user
# returns a dict {field_name: error_message}, or None if validation passes
errors = validate_myform(request.POST)
if errors is None:
# save the data and redirect elsewhere
save_myform(request.POST)
return HTTPFound('/')
else:
return {
'page_title': 'Validation error!',
'errors': errors,
'data': request.POST,
}
在模板中,您只需注意使用数据预先填充输入:
<input type="text" name="first_name" value="${data.get('first_name, '')}" />
并在视图函数传递验证消息时呈现验证消息:
%if 'first_name' in errors:
<span class="error">${errors['first_name']}</span>
%endif
表单库(变形等)负责管道,但原理是相同的 - 视图函数接收POST请求,验证数据并使用相同的数据和错误消息重新呈现表单(如果有的话)。 / p>