django-hashid-field icon indicating copy to clipboard operation
django-hashid-field copied to clipboard

Add Django path converter for HashID

Open wowkin2 opened this issue 5 years ago • 1 comments
trafficstars

Created Django path converter using official documentation. I use it instead of slug, because last one allows extra symbols which breaks desired logic.

Probably it can be useful for somebody else. If needed I can create a PR for this project.

""" Django file `blog_app/urls.py` """

from django.urls import path, register_converter

from . import views
from .constants import HASHID_ALPHABET, HASHID_MIN_LENGTH

# Example:
# HASHID_ALPHABET = 'abcdefABCDEF1234567890'
# HASHID_MIN_LENGTH = 7


class HashidPathConverter:
    regex = '[' + HASHID_ALPHABET + ']{' + str(HASHID_MIN_LENGTH) + ',}'

    @staticmethod
    def to_python(value):
        return value

    @staticmethod
    def to_url(value):
        return str(value)


register_converter(HashidPathConverter, 'hashid')


urlpatterns = [
    # ...
    path('blog/<hashid:post_id>--<slug:slug>/', views.view_blog_post, name='blog_post'),
    # ...
]

wowkin2 avatar May 27 '20 12:05 wowkin2

Yeah I had the same thought back when the new path stuff came out in Django 2. I was thinking of creating a generic converter that would work with the default alphabet and min_length, but then also a converter_factory that you could pass a field into, and it would create a converter on the fly that verified paths based on that field's specific alphabet and min_length. Maybe for a future version.

nshafer avatar May 28 '20 18:05 nshafer