Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom validation of Django inline formset
class ProductAutochangeInlineFormSet(
forms.inlineformset_factory(ProductAutochangeSet, ProductAutochange, form=ProductAutochangeForm, extra=1)):
def clean(self):
super(ProductAutochangeInlineFormSet, self).clean()
product_pks = []
num_productautochanges = 0
for form in self.forms:
if not form.is_valid():
continue
if form.cleaned_data and not form.cleaned_data.get('DELETE'):
num_productautochanges += 1
if form.cleaned_data["product"].pk in product_pks:
form.add_error("product", "Product {} cannot be autochanged multiple times.".format(
form.cleaned_data["product"]))
else:
product_pks.append(form.cleaned_data["product"].pk)
if num_productautochanges < 1:
raise ValidationError("At least one product autochange needs to be defined.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.