- Author:
- dcwatson
- Posted:
- September 13, 2012
- Language:
- Python
- Version:
- Not specified
- 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
- Add custom fields to the built-in Group model by jmoppel 1 month, 2 weeks ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 4 months, 4 weeks ago
- Python Django CRUD Example Tutorial by tuts_station 5 months, 2 weeks ago
- Browser-native date input field by kytta 6 months, 4 weeks ago
- Generate and render HTML Table by LLyaudet 7 months, 1 week ago
Comments
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.
#
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.