Optional Trailing Slashes

A snippet showing how to handle trailing slashes in URLs.


# models.py

from django.db import models

class Page(models.Model):
    slug = models.SlugField(unique=True)
      

# admin.py

from django.contrib import admin
from .models import Page

@admin.register(Page)
class PageAdmin(admin.ModelAdmin):
    list_display = ("slug",)
      

# settings.py
APPEND_SLASH = True   # auto-redirects /path to /path/

# urls.py example using re_path for optional slash:
 from django.urls import re_path
 from . import views
 urlpatterns = [
     re_path(r"^docs/?$", views.docs, name="docs"),
 ]
      
Explanation:
  • APPEND_SLASH=True auto-redirects to slash-suffixed URLs when suitable.
  • Use re_path(.../?$) to accept both with and without trailing slash.
  • Category URLs & Routing
  • Total Views 592
  • Last Modified 05 April, 2026
  • Tags #urls #trailing slash #config #routing
Previous snippet
UUID Converter in URLs
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.