Django slug

Have you ever seen url's that look like this: http://127.0.0.1:8000/detail-view-class-based-views-django. The detail-view-class-based-views-django is called a slug.It is a description containing only letters, hyphens, numbers or underscores.It is often used in url's to make them easier to read, but also to make them more search engine friendly.

Modify the models.py File

Open the models.py file and add a field called slug with the data type SlugField:



from django.db import models

# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField(blank=True, default="")
    slug = models.SlugField(max_length=200)
    published = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-published',)

    def __str__(self):
        return self.title


Change Admin

Now we have a new field in the database, but we also want this field to be updated automatically when we set the title or body.

This can be done with a built-in Django feature called prepopulated_fields where you specify the field you want to pre-populate, and a tuple with the field(s) you want to populate it with.

This is done in the admin.py file:


from django.contrib import admin
from . import models

# Register your models here.

@admin.register(models.Article)
class ArticleAdmin(admin.ModelAdmin):
	prepopulated_fields = {'slug': ('title',), }

Or,


from django.contrib import admin
from . import models

# Register your models here.

class ArticleAdmin(admin.ModelAdmin):
	prepopulated_fields = {'slug': ('title',), }

admin.site.register(models.Article, ArticleAdmin)

Latest Blog