私は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列が必要です。required-nessを追加することはできますが、削除することはできません。」と記載されていますが、NULL以外の空の文字列を許可したいので、許可しvalidators.required
ません。blank=True, null=False
Djangoに何かありますか?
より正確には、以下のようなカスタムバリデーターを使用して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
のは、それも適切な解決策ではないように思われるからです。
そのような場合にフォームを検証する正しい方法は何ですか?事前にご提案ありがとうございます。