Django中的内联形式验证 [英] Inline Form Validation in Django

查看:139
本文介绍了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天全站免登陆