About Custom URL Path Converters

When the default URL path converters (str, int, slug, uuid, path) are not enough, instead of using re_path, it's cleaner to define a custom reusable path converter.

Here's an example of two path converters which keep the year and month of 4 and 2 digits respectively:

from django.urls import path, register_converter
from . import views

class FourDigitYearConverter:
    regex = "[0-9]{4}"

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return "%04d" % value

class TwoDigitMonthConverter:
    regex = "[0-9]{2}"

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return "%02d" % value

register_converter(FourDigitYearConverter, "yyyy")
register_converter(TwoDigitMonthConverter, "mm")

urlpatterns = [
    path("", views.post_list, name="post_list"),
    path(
        "<yyyy:yyyy>/<mm:mm>/<slug:slug>/", 
        views.post_details, 
        name="post_details"
    ),
]

Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2