Login

Unique field inline formset

Author:
dcwatson
Posted:
September 13, 2012
Language:
Python
Version:
Not specified
Tags:
field unique formset inlineformset
Score:
0 (after 0 ratings)

This method will return an inline formset class that validates values across the given field are unique among all forms. For instance:

ApprovedUserFormSet = inlineformset_factory(Request, ApprovedUser, formset=unique_field_formset('email'), form=ApprovedUserForm)

Will make sure all ApprovedUser objects created for the Request have unique "email" fields.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def unique_field_formset(field_name):
    from django.forms.models import BaseInlineFormSet
    class UniqueFieldFormSet (BaseInlineFormSet):
        def clean(self):
            if any(self.errors):
                # Don't bother validating the formset unless each form is valid on its own
                return
            values = set()
            for form in self.forms:
                value = form.cleaned_data[field_name]
                if value in values:
                    raise forms.ValidationError('Duplicate values for "%s" are not allowed.' % field_name)
                values.add(value)
    return UniqueFieldFormSet

More like this

  1. InlineFormset Template by petry 6 years, 9 months ago
  2. Printing inline formsets as UL / P by ikke 6 years ago
  3. Embedded inline formsets in ModelForm by stan 4 years, 9 months ago
  4. Handles Inline Formsets and also "in-standard-way" normal forms by sebnapi 3 years, 6 months ago
  5. Arbitrary length formset by Rupe 5 years, 12 months ago

Comments

monikkinom (on March 6, 2015):

If the errors are not visible in the view, you are probably making the same mistake I made. To display the validation errors in the view, you must add {{ formset.non_form_errors }} to it.

#

Please login first before commenting.