1class RequiredImageInlineFormset(forms.models.BaseInlineFormSet):
2 """ Makes inline fields required """
3
4 def clean(self):
5 # get forms that actually have valid data
6 count = 0
7 delete_checked = 0
8 for form in self.forms:
9 try:
10 if form.cleaned_data:
11 count += 1
12 if form.cleaned_data['DELETE']:
13 delete_checked += 1
14 if not form.cleaned_data['DELETE']:
15 delete_checked -= 1
16 except AttributeError:
17 # annoyingly, if a subform is invalid Django explicity raises
18 # an AttributeError for cleaned_data
19 pass
20
21 # Case no images uploaded
22 if count < 1:
23 raise forms.ValidationError(
24 'At least one image is required.')
25
26 # Case one image added and another deleted
27 if delete_checked > 0 and ProductImage.objects.filter(product=self.instance).count() == 1:
28 raise forms.ValidationError(
29 "At least one image is required.")
30