我正在使用pyramid_simpleform构建一个Form对象。我想有一个方法来构建表单对象,一旦提交它就会尝试验证它。
如果输入有效,我会将用户重定向到确认页面。否则,我将呈现一个错误页面。我正在使用form.validate()来查看输入数据是否适合模式。
如果表单尚未提交,我想使用render_to_response显示表单。如何检测表单是否已提交?
答案 0 :(得分:2)
if request.method == "POST":
您应该将逻辑拆分为两个不同的视图函数。
此外,您应该返回一个表单渲染器以供模板使用,而不是在视图函数中直接渲染表单。例如:
<强> ./ forms.py:强>
from formencode import Schema, validators
class RegistrationForm(Schema):
email = validators.Email(not_empty=True, strip=True)
password = validators.UnicodeString(not_empty=True)
password_confirm = validators.UnicodeString()
chained_validators = [validators.FieldsMatch(
'password', 'password_confirm',
messages=dict(invalidNoMatch=u'Password does not match'))]
<强> ./视图/ accounts.py:强>
from pyramid_simpleform import Form
from pyramid_simpleform.renderers import FormRenderer
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from pyramid.url import route_url
from ..forms import RegistrationForm
from ..models import DBSession, User
@view_config(route_name='accounts_register', renderer='/accounts/register.mako',
request_method='GET')
def register(request):
"""Shows the empty form."""
form = Form(request, schema=RegistrationForm)
return {'renderer': FormRenderer(form)}
@view_config(route_name='accounts_register', renderer='/accounts/register.mako',
request_method='POST')
def register_post(request):
"""Receives the posted form."""
form = Form(request, schema=RegistrationForm)
if form.validate():
user = User(form.data['email'], form.data['password'])
DBSession.add(user)
return HTTPFound(route_url('profile', request))
return {'renderer': FormRenderer(form)}
<强> ./模板/账户/ register.mako:强>
<form action="" method="post">
<div class="${' error' if renderer.is_error('email') else ''}">
<label for="email">Email</label>
${renderer.text('email', type='email', placeholder='Email')}
% if renderer.is_error('email'):
<span class="errors">${', '.join(renderer.errors_for('email'))}</span>
% endif
</div>
<!-- ... --->
</form>
答案 1 :(得分:1)
如果您有请求对象,则可以测试它的“POST”方法。
if request.method == "POST":