【发布时间】:2010-11-30 09:39:55
【问题描述】:
我是 FormAlchemy 的新手,我似乎没有得到任何东西。我有一个这样定义的 SQLAlchemy 模型:
...
class Device(meta.Base):
__tablename__ = 'devices'
id = sa.Column('id_device', sa.types.Integer, primary_key=True)
serial_number = sa.Column('sn', sa.types.Unicode(length=20), nullable=False)
mac = sa.Column('mac', sa.types.Unicode(length=12), nullable=False)
ipv4 = sa.Column('ip', sa.types.Unicode(length=15), nullable=False)
type_id = sa.Column('type_id', sa.types.Integer,
sa.schema.ForeignKey('device_types.id'))
type = orm.relation(DeviceType, primaryjoin=type_id == DeviceType.id)
...
然后在我的(Pylons)控制器中创建一个 FormAlchemy 表单,如下所示:
c.device = model.meta.Session.query(model.Device).get(device_id)
fs = FieldSet(c.device, data=request.POST or None)
fs.configure(options=[fs.ipv4.label(u'IP').readonly(),
fs.type.label(u'Type').with_null_as((u'—', '')),
fs.serial_number.label(u'S/N'),
fs.mac.label(u'MAC')])
文档说“默认情况下,NOT NULL 列是必需的。您只能添加必需性,而不是删除它。”,但我想允许非 NULL 空字符串,validators.required 不允许。 Django中有blank=True, null=False之类的东西吗?
更准确地说,我想要一个像下面这样的自定义验证器,允许使用 type=None 的空字符串或将所有值设置为非 NULL 和非空:
# For use on fs.mac and fs.serial_number.
# I haven't tested this code yet.
def required_when_type_is_set(value, field):
type_is_set = field.parent.type.value is not None:
if value is None or (type_is_set and value.strip() = ''):
raise validators.ValidationError(u'Please enter a value')
如果可能的话,我想避免给猴子打补丁formalchemy.validators.required 或其他东西。我不想在模型字段上设置nullable=True,因为它似乎也不是正确的解决方案。
在这种情况下验证表单的正确方法是什么?提前感谢您的任何建议。
【问题讨论】:
标签: python sqlalchemy validation pylons formalchemy