django-hashid-field
django-hashid-field copied to clipboard
Add Django path converter for HashID
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'),
# ...
]
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.