Skip to content

Instantly share code, notes, and snippets.

@jmorakuebler
Last active April 23, 2020 14:08
Show Gist options
  • Save jmorakuebler/7a89607c40d5ba97757ebe9db162743c to your computer and use it in GitHub Desktop.
Save jmorakuebler/7a89607c40d5ba97757ebe9db162743c to your computer and use it in GitHub Desktop.
Custom BaseInlineFormSet to check for duplicates in a inline formset
class CustomBaseInlineFormSet(BaseInlineFormSet):
"""
Custom BaseInlineFormSet with overridden clean method to look for
duplicates in the inline formset.
A message will appear under the offending field.
The field to be evaluated must be provided.
Attributes
field_name(string): name of the field to be verified. Default is None
msg (string): the message that will appear under the field. Default
value is 'Duplicated field'
"""
field_name = None
msg = 'Duplicated field'
def clean(self):
if self.field_name is None:
raise ImproperlyConfigured('field_name was not provided.')
super().clean()
if any(self.errors):
return
field_name = self.field_name
msg = self.msg
records = []
for form in self.forms:
if field_name in form.cleaned_data:
field = form.cleaned_data[field_name]
if field in records:
form.add_error(
field_name, ValidationError(msg, code='invalid')
)
records.append(field)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment