Django 中的内联表单验证 [英] Inline Form Validation in Django

查看:40
本文介绍了Django 中的内联表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想强制管理更改表单中的整个内联表单集.因此,在我当前的场景中,当我在发票表单(在管理员中)点击保存时,内联订单表单是空白的.我想阻止人们在没有关联订单的情况下创建发票.

I would like to make an entire inline formset within an admin change form compulsory. So in my current scenario when I hit save on an Invoice form (in Admin) the inline Order form is blank. I'd like to stop people creating invoices with no orders associated.

有人知道一种简单的方法吗?

Anyone know an easy way to do that?

模型字段上的 (required=True) 之类的正常验证在这种情况下似乎不起作用.

Normal validation like (required=True) on the model field doesn't appear to work in this instance.

推荐答案

做到这一点的最佳方法是定义一个自定义表单集,使用一个干净的方法来验证至少存在一个发票订单.

The best way to do this is to define a custom formset, with a clean method that validates that at least one invoice order exists.

class InvoiceOrderInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        # get forms that actually have valid data
        count = 0
        for form in self.forms:
            try:
                if form.cleaned_data:
                    count += 1
            except AttributeError:
                # annoyingly, if a subform is invalid Django explicity raises
                # an AttributeError for cleaned_data
                pass
        if count < 1:
            raise forms.ValidationError('You must have at least one order')

class InvoiceOrderInline(admin.StackedInline):
    formset = InvoiceOrderInlineFormset


class InvoiceAdmin(admin.ModelAdmin):
    inlines = [InvoiceOrderInline]

这篇关于Django 中的内联表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆