dkoug Blog

Django slug field validator

Django -- Posted on Nov. 9, 2017

Django slug field validator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class SlugValidator:
    def clean_slug(self):
        slug = self.cleaned_data['slug']
        existing_objects = self.Meta.model.objects.filter(slug=slug)
        if self.instance:
            existing_objects = existing_objects.exclude(
                pk=self.instance.pk)
        if existing_objects:
            raise ValidationError('The slug already exists')
        return slug