SoFunction
Updated on 2024-10-26

Django implementation of custom routing converter

Custom path converter

Sometimes the built-in url converters above don't meet our needs, so django provides us with an interface that allows us to define our own url converters

django built-in path converter source code analysis

Before we customize the route converter, let's check how those built-in route converters in django are written, source path from

import converters

class IntConverter:
    regex = '[0-9]+'

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

    def to_url(self, value):
        return str(value)


class StringConverter:
    regex = '[^/]+'

    def to_python(self, value):
        return value

    def to_url(self, value):
        return value


class UUIDConverter:
    regex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'

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

    def to_url(self, value):
        return str(value)


class SlugConverter(StringConverter):
    regex = '[-a-zA-Z0-9_]+'


class PathConverter(StringConverter):
    regex = '.+'


DEFAULT_CONVERTERS = {
    'int': IntConverter(),
    'path': PathConverter(),
    'slug': SlugConverter(),
    'str': StringConverter(),
    'uuid': UUIDConverter(),
}


REGISTERED_CONVERTERS = {}


def register_converter(converter, type_name):
    REGISTERED_CONVERTERS[type_name] = converter()
    get_converters.cache_clear()

From the above we can see very analytically that django's built-in path converter is first defined as a class, which defines a class attribute regex as the value of the regular expression, then defines 2 methods to_python and to_url, and finally defines a register_converter function to register the path converter to the django

We've divided him into 5 steps here:

1. Create one and define a class in the file.
2. Define a property regex in the class, this property is used to save the regular expression of the url converter rule.
3. Implement the to_python(self,value) method, which converts the value in the url and passes it to the view function.
4. implement to_url(self,value) method, this method is to do url reversal when the parameters passed in will be converted and spliced into a correct url.
5. Define the converter and register it with django.

small case

Next we define our own converter that satisfies the 4-digit path matching
Create a new file with the following code:

class FourDigitYearConverter:
    # Define regular expressions
    regex = '[0-9]{4}'

    def to_python(self, value):
        return value

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

Register customized converters under File

from  import path,  converters
# Register custom converters
register_converter(, 'yyyy')  # yyyy is the type name of the custom converter
urlpatterns = [
  path('articles/<yyyy:year>', views.articles_yyyy),
]

This way we can match the 4-digit url address

To this article on the implementation of Django custom routing converter to this article , more related Django routing converter content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more !