Use Enums in URLs

django-enum provides a converter that can be used to register enum url parameters with the Django path resolver.

from enum import IntEnum

from django.http import HttpResponse
from django.urls import path

from django_enum.urls import register_enum_converter


class Enum1(IntEnum):
    A = 1
    B = 2


register_enum_converter(Enum1)
register_enum_converter(Enum1, type_name="Enum1ByName", prop="name")


def enum_converter_view(request, enum):
    assert isinstance(enum, Enum1)
    return HttpResponse(status=200, content=f"{enum=}")


app_name = "examples"

urlpatterns = [
    # this will match paths /1 and /2
    path("<Enum1:enum>", enum_converter_view, name="enum_default"),

    # this will match paths /A and /B
    path("<Enum1ByName:enum>", enum_converter_view, name="enum_by_name"),
]

By default the converter will use the value property of the enumeration to resolve the enumeration, but this can be overridden by passing the prop parameter, so we could for example use the name or label instead.

The reversals for the above paths would look like this:

    from .filterfield_howto import TextChoicesExampleFilterViewSet
    from .filterset_howto import (
        TextChoicesExampleFilterViewSet as TextChoicesExampleFilterSetViewSet
    )
    from .flagfilterfield_howto import FlagExampleFilterViewSet

    app_name = "howto"

    urlpatterns = [
        path(
            'filterfield/',
            TextChoicesExampleFilterViewSet.as_view(),
            name='filterfield'
        ),
        path(
            'filterset/',
            TextChoicesExampleFilterSetViewSet.as_view(),
            name='filterset'
        ),
        path('flagfilterfield/', FlagExampleFilterViewSet.as_view(), name="flagfilterfield")
    ]
except ImportError:
    urlpatterns = []