Reputation: 27139
I want this to fail:
MyModelWithSlug.objects.create(name='Foo', slug='abc . ü')
The string abc . ü
is not a valid slug in django.
How to make above line fail?
Upvotes: 2
Views: 4148
Reputation: 905
Read Alasdair's comment on OP
Django provides a hook called CLEAN to add custom validation but beware Django doesn't call it automatically on either save
or create
. So you have to override save()
on model as well.(Thanks to @alasdair for correcting me.)
So the model becomes:
class MyModelWithSlug(models.Model):
name = models.CharField(max_length=200, default="")
slug = models.CharField(max_length=200, null=True, blank=True)
def clean(self):
# will raise an Validation Error even if unicode is present. refer validate_unicode_slug
self.slug = validators.validate_slug(self.slug)
def save(self):
self.full_clean() # calls self.clean() as well cleans other fields
return super(MyModelWithSlug, self).save(*args, **kwargs)
class MyModelWithSlug(models.Model):
name = models.CharField(max_length=200, default="")
slug = models.SlugField(max_length=200, null=True, blank=True)
Upvotes: 4