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. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 6 months, 1 week ago
  2. Crispy Form by sourabhsinha396 7 months ago
  3. ReadOnlySelect by mkoistinen 7 months, 2 weeks ago
  4. Verify events sent to your webhook endpoints by santos22 8 months, 2 weeks ago
  5. Django Language Middleware by agusmakmun 8 months, 3 weeks 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.

#

dimkoug (on May 24, 2020):

A minor change

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: if form.cleaned_data: 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

#

Please login first before commenting.