liveBook · Manning

Slugify()

As explained in Django in Action

slugify() is a Django utility function that converts text into a lowercase, URL-compatible slug.

slugify() converts text into a lowercase, URL-compatible slug. It normalizes Unicode to ASCII, trims surrounding spaces, turns remaining whitespace into single dashes, and removes characters outside letters, numbers, underscores, and hyphens. section 11.2.2

The transformation follows a practical web-friendly cleanup sequence:

  • Convert Unicode characters to ASCII where possible. section 11.2.2
  • Lowercase the result and remove leading or trailing spaces. section 11.2.2
  • Replace internal whitespace with one hyphen and remove disallowed characters. section 11.2.2
Listing 11.7 API endpoint for fetching a Venue object
# RiffMates/bands/api.py
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.text import slugify

from ninja import Router, ModelSchema

from bands.models import Venue

router = Router()  #1

class VenueOut(ModelSchema):
    slug: str  #2
    url: str

    class Meta:
        model = Venue
        fields = ["id", "name", "description"]  #3

    @staticmethod
    def resolve_slug(obj):  #4
        slug = slugify(obj.name) + "-" + str(obj.id)
        return slug

    @staticmethod
    def resolve_url(obj):  #5
        url = reverse("api-1.0:fetch_venue", args=[obj.id, ])
        return url

@router.get("/venue/{venue_id}/",
    response=VenueOut,
    url_name="fetch_venue")  #6
def fetch_venue(request, venue_id):
    venue = get_object_or_404(Venue, id=venue_id)
    return venue

A Django Ninja serializer calls slugify() on a Venue name, then appends the object ID to create values such as cbgb-1. section 11.2.2

Generated API field

For a Venue named “CBGB”, resolve_slug() produces “cbgb-1”. The suffix comes from the serializer's application code, not from slugify() itself. section 11.2.2

How Django in Action covers it

How deep it goes
Explains the complete text-normalization behavior but does not descend into implementation internals.
Examples
Uses a CBGB Venue name and produces the serialized slug cbgb-1.
What it assumes
Assumes familiarity with Django model objects and serializer fields while demonstrating the normalization rules directly.
What you can do after
Apply it via django.utils.text.slugify() to normalize text before exposing it in an API field.
How it connects
Connects Django utilities with Django Ninja serializers, model objects, and URL construction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.