vero4karu
12/16/2014 - 3:57 PM

Django: validate inline form in main form

Django: validate inline form in main form

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,
    ]