我正在使用 Pyramid 和 FormEncode 来尝试创建和验证地址列表。我正在使用 pyramid_simpleform 并一直在查看本教程http://jimmyg.org/blog/2007/multiple-checkboxes-with-formencode.html和上一个问题Pylons FormEncode with a array of form elements但我还在有一些问题。我的结构目前如下:
架构:
from formencode import Schema, validators, ForEach, NestedVariables
class AddressSchema(Schema):
allow_extra_fields = False
addresses = validators.String(not_empty=True)
class JobSchema(Schema):
filter_extra_fields = True
allow_extra_fields = True
pre_validators = [NestedVariables()]
job_name = validators.MinLength(5, not_empty=True)
comments = validators.MinLength(5, not_empty=False)
addresses = ForEach(AddressSchema())
模板:
${renderer.errorlist("addresses")}
${renderer.errorlist("job_name")}
<p><label for="job_name">Job name: </label>${renderer.text("job_name", size=30)}</p>
% for a in range(1, initial_number_of_address_fields):
<p><label for="addresses-${a}">Address: </label>${renderer.textarea("addresses-" + str(a), cols=39, rows=6)}</p>
% endfor
${renderer.submit("submit", "Submit")}
看法:
@view_config(route_name='add_addresses', renderer="add_addresses.mak")
def add_addresses(request):
from myproject.forms import JobSchema
from myproject.models import Job
from formencode import htmlfill, variabledecode, ForEach
initial_number_of_address_fields = 5
form = Form(request, schema=JobSchema(), variable_decode=False)
renderer = FormRenderer(form)
# if the form has been submitted
if 'submit' in request.POST:
if form.validate(): # uses validation specified in forms.py
# automatically bind to provided form
obj = form.bind(Job()) # no exisiting id provided, so a new document is created
# add some additional values
obj.__setattr__("last_updated_on", datetime.date.today().strftime('%Y/%m/%d'))
#save
obj.save()
return HTTPFound(location="/")
return {
'title':'Add addresses',
'initial_number_of_address_fields': initial_number_of_address_fields,
'renderer': renderer
}
我得到了像这样的实际验证错误:
{'addresses': u'Missing value'}
但正确填写的值也会产生错误:
输入必须是dict-like(不是:u'dgfgfd')
如果我更改variable_decode
为True
(在表单变量设置中),我将不再收到任何错误。我想我应该以variable_decode
某种方式使用,但我不确定如何使用。如何正确验证这些值?