【问题标题】:Django - Add form validation to inlineformset_factoryDjango - 将表单验证添加到 inlineformset_factory
【发布时间】:2021-09-23 16:12:36
【问题描述】:

因此,我正在尝试验证 inlineformset_factory 对象中的某些字段,但我不知道如何从该视图中以干净的方式执行此操作(不使用 Form 类)。

在这种情况下是否可以覆盖 .is_valid() 方法?

任何帮助将不胜感激。

def tenant(request, id):
    tenant = Tenant.objects.get(id=id)

    DealerFormset = inlineformset_factory(Tenant, Dealer, fields=('name', 'phone_number'), extra=0)
    formset = DealerFormset(instance=tenant)

    if request.method == 'POST':
        formset = DealerFormset(request.POST, instance=tenant)
        if formset.is_valid(): # <---  How to add custom validations here?
            formset.save()                

        return redirect('tenant_details', id=tenant.id)

    context = {
        'formset': formset,
    }

    return render(request, 'tenant_details.html', context)

【问题讨论】:

    标签: python django formset inline-formset


    【解决方案1】:

    由于您使用inlineformset_factory 创建集合,我建议继承BaseInlineFormSet 并实现clean 方法。一旦你有一个自定义的FormSet 类,你可以通过formset 关键字参数将它传递给inlineformset_factory。以下内容应该适用于您当前的设计:

    from django.forms import (
        BaseInlineFormSet, inlineformset_factory
    )
    
    # Make a custom FormSet class and implement the clean method
    # to customize the validation
    class CustomInlineFormSet(BaseInlineFormSet):
        def clean():
            # Implement your custom validation here
    
    # Use your custom FormSet class as an argument to inlineformset_factory
    DealerFormset = inlineformset_factory(
        Tenant, Dealer, fields=('name', 'phone_number'),
        extra=0, formset=CustomInlineFormSet
    )
    

    DealerFormset 现在可以使用了,因为它同时具有基本验证和自定义验证。

    【讨论】:

    • 谢谢,将在我的代码中尝试这个并返回一些 cmets
    【解决方案2】:

    您基本上需要基于BaseInlineFormSet 类创建自己的表单集。您可以查看 django 文档 here 以获取更多信息,但这并没有什么复杂的。

    然后,您将通过添加要用作参数的表单集来创建表单集:

    formset_factory(TestForm, formset=BaseTestFormSet)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      相关资源
      最近更新 更多