Note: Please dont consider it as duplicate post, all the existing posts are not giving clear understanding of SlugField.
My question is "we can sluggify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?"
For example, in my model, I have a field called
url = models.CharField(max_length=30)
def save(self, ...):
self.url = slugify(self.url)
.......
Won't the url be saved in slugified format in database? I can use this slugified value in browser right, then what is the use of creating models.SlugFIeld(max_length=30)? What advantage SlugField will add over slugified CharField?
In above code, how replacing "CharField" with "SlugField" be advantageous?
We can
slugifyand store the value in a CharField right? then why do we need SlugField for something that can be done easily usingCharField?
A SlugField is a CharField, but a special CharField. It is a field that contains a validator that will, if you for example enter data through a form, validate if the entered string is indeed a slug. For example a slug does not contain whitespace, so if you would use the SlugField in a form, such that an author can specify the slug themselve, it will reject such slugs.
By default it uses the django.core.validators.validate_slug validator [GitHub]. The SlugField has an extra parameter allow_unicode. If this is set to True, it will use the django.core.validators.validate_unicode_slug validator [GitHub].
So in essence it is indeed a CharField, but with a validator that is determined by the **allow_unicode=… parameter [Django-doc]. This thus makes it more convenient.
Often you do not want to slugify the content of the slug field itself, but from another field, for example the title of a blog post entry. You thus still want to preserve the title, but make a slugified variant.
The django-autoslug package [readthedocs] provides an AutoSlugField [readthedocs] which is more convenient, since you can define how to populate the field, and thus it will automatically slugify:
from autoslug import AutoSlugField
class MyModel(models.Model):
title = models.CharField(max_length=128)
slug = AutoSlugField(populate_from='title')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With