Django HashID URL Converter

November 10, 2020

HashID’s allow you to convert an integer into a “unique” short string.

If you Django HashID Field, you’ll want to create a custom path converter so you can accept them in URL’s.

from hashids import Hashids

def hashid_converter_factory(min_length=0, alphabet=Hashids.ALPHABET)
    """
    Factory function to create a Django URL path converter for HashID's using a
    specific min_length and alphabet.
    """
    class HashIdConverter:
        regex = r'[{}]{{}}'.format(min_length, alphabet)

        def to_python(self, value):
            return value

        def to_url(self, value):
            return value.hashid

    return HashIdConverter

Note: You can skip the factory function and just define a normal class with your own min_length/alphabet values for simplicity.

With that defined, you can simply register the converter and use it in your urlpatterns.

from django.urls import include, path, register_converter

register_converter(hashid_converter_factory(min_length=7), 'hashid')

urlpatterns = [
    path('codes/<hashid:pk>/', ...)
]

Return home