Skip to content

Instantly share code, notes, and snippets.

@klebercode
Last active February 4, 2016 18:52
Show Gist options
  • Save klebercode/286a2ae0b0e596eba1c9 to your computer and use it in GitHub Desktop.
Save klebercode/286a2ae0b0e596eba1c9 to your computer and use it in GitHub Desktop.
from django import forms
from django.core.exceptions import ValidationError
def clean_unique(form, field, exclude_initial=True,
format="The %(field)s %(value)s has already been taken."):
value = form.cleaned_data.get(field)
if value:
qs = form._meta.model._default_manager.filter(**{field:value})
if exclude_initial and form.initial:
initial_value = form.initial.get(field)
qs = qs.exclude(**{field:initial_value})
if qs.count() > 0:
raise forms.ValidationError(format % {'field':field, 'value':value})
return value
# Usage:
class DeployForm(forms.ModelForm):
"""We want both the slug and cname fields to be unique"""
class Meta:
model = Website
fields = ['slug', 'cname']
def clean_slug(self):
return clean_unique(self, 'slug')
def clean_cname(self):
return clean_unique(self, 'cname')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment