Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nspo
Created April 21, 2017 19:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nspo/cd26ae2716332234757d2c3b1f815fc2 to your computer and use it in GitHub Desktop.
Save nspo/cd26ae2716332234757d2c3b1f815fc2 to your computer and use it in GitHub Desktop.
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