【问题标题】:django validate multiple inline formsdjango 验证多个内联表单
【发布时间】:2013-11-15 10:16:24
【问题描述】:

我正在使用 Django 管理界面和 Modelform 表单验证。

我的一个模型有问题,我想不出一种方法让内联表单检查字段的唯一性。例如,有两个带有“名称”字段的内联对象。如果两者都包含相同的名称,我想提出一个验证错误。

据我所知,每个内联都作为单独的表单进行验证,因此很难将它们绑定并检查。

(非常)基本的想法:

Class Parent        
    name    charfield
    inlines [Child]

Class Child
    name    charfield   <- I'd like to make sure this is unqiue within the inlines
    age     intfield

【问题讨论】:

标签: django forms validation


【解决方案1】:

您编写自己的 FormSet 类,并创建一个干净的可调用对象:

class BaseDateFormSet(BaseInlineFormSet):
'''run some validation on the forms dates values'''

def clean(self):
    super(BaseDateFormSet, self).clean()
    if any(self.errors):
        return
    for form in self.forms:
        start_date = form.cleaned_data.pop('start_date', None)
        end_date = form.cleaned_data.pop('end_date', None)

        if start_date and end_date:
            if start_date >= end_date:
                raise ValidationError("The end date is before the start date.")

要使用,请传入表单集工厂:

    MyFormSet = inlineformset_factory(<parent model class>, <model class>, \
                         extra=1, formset=BaseDateFormSet)

【讨论】:

  • 谢谢,这看起来很有希望 - 我明天会尝试将其插入。现在无法访问代码
猜你喜欢
  • 2023-04-09
  • 2016-03-15
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 2011-06-02
  • 2011-09-17
  • 2013-09-03
  • 1970-01-01
相关资源
最近更新 更多