python Django:验证主要表单中的内联表单

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django:验证主要表单中的内联表单相关的知识,希望对你有一定的参考价值。

![Admin](http://habrastorage.org/files/c0c/fa9/7a0/c0cfa97a0be04be4bc2f4c81359c9984.png)
![Admin](http://hsto.org/files/acc/8bd/7b6/acc8bd7b69984559a70644d4e378185c.png)
from django import forms
from product.models import Equipment


class EquipmentForm(forms.ModelForm):
    class Meta:
        model = Equipment

    def clean(self):
        cleaned_data = super(EquipmentForm, self).clean()
        is_active = cleaned_data.get('is_active')
        subcategories = cleaned_data.get('subcategories')

        has_active_images = False
        gallery_count = int(self.data.get('gallery-TOTAL_FORMS', 0))
        for i in range(0, gallery_count):
            try:
                if self.data.get('gallery-{0}-is_active'.format(i), '') == 'on':
                    has_active_images = True
            except ValueError:
                pass

        if is_active and not subcategories:
            msg = u'No se puede activar la página sin al menos una subcateroría.'
            self.add_error('is_active', msg)
        if is_active and not has_active_images:
            msg = u'No se puede activar la página sin al menos una imagen activa.'
            self.add_error('is_active', msg)
from django.contrib import admin

from product.forms import EquipmentForm

@admin.register(Equipment)
class EquipmentAdmin(admin.ModelAdmin):
    form = EquipmentForm
    
    inlines = [
        EquipmentGalleryInline,
    ]

以上是关于python Django:验证主要表单中的内联表单的主要内容,如果未能解决你的问题,请参考以下文章

带有内联表单集的 Django 表单验证

如何从 django 中的内联表单接收上传的文件?

将查询集传递给 django 内联表单中的外键字段

Python自动化运维系列之Django Form表单验证

Django 表单验证:在父表单中获取子表单数据

Django - 禁用表单选择字段验证