Created
April 21, 2017 19:47
-
-
Save nspo/cd26ae2716332234757d2c3b1f815fc2 to your computer and use it in GitHub Desktop.
Custom validation of Django inline formset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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