Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

validate delete inline formset django

class RequiredImageInlineFormset(forms.models.BaseInlineFormSet):
    """ Makes inline fields required """

    def clean(self):
        # get forms that actually have valid data
        count = 0
        delete_checked = 0
        for form in self.forms:
            try:
                if form.cleaned_data:
                    count += 1
                    if form.cleaned_data['DELETE']:
                        delete_checked += 1
                    if not form.cleaned_data['DELETE']:
                        delete_checked -= 1
            except AttributeError:
                # annoyingly, if a subform is invalid Django explicity raises
                # an AttributeError for cleaned_data
                pass

        # Case no images uploaded
        if count < 1:
            raise forms.ValidationError(
                'At least one image is required.')

        # Case one image added and another deleted
        if delete_checked > 0 and ProductImage.objects.filter(product=self.instance).count() == 1:
            raise forms.ValidationError(
                "At least one image is required.")
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #validate #delete #inline #formset #django
ADD COMMENT
Topic
Name
9+7 =