Skip to content

Instantly share code, notes, and snippets.

@cansadadeserfeliz
Last active March 10, 2022 12:13
Show Gist options
  • Select an option

  • Save cansadadeserfeliz/1c065cb54baef2da79c2 to your computer and use it in GitHub Desktop.

Select an option

Save cansadadeserfeliz/1c065cb54baef2da79c2 to your computer and use it in GitHub Desktop.
Django: validate inline form in main form
from django.contrib import admin
from product.forms import EquipmentForm
@admin.register(Equipment)
class EquipmentAdmin(admin.ModelAdmin):
form = EquipmentForm
inlines = [
EquipmentGalleryInline,
]
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)
@leesanghyun0414
Copy link

Wonderful solutions!
You save me .
Thank you !

@thiagolara
Copy link

Awesome!! It works perfect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment