passing url parameters using custom url converter in django

205 Views Asked by At

I am getting this error when I use my custom url converter

Reverse for 'user-update' with keyword arguments '{'pk': 'Rwdr4l3D'}' not found. 1 pattern(s) tried: ['users/(?P<pk>[a-zA-Z0-9](8,))/update/\\Z']

Question: why isn't the pk matching the regex whats wrong details given below

urls.py

from utils.url import HashIdConverter
register_converter(HashIdConverter, "hashid")
app_name = "users"
urlpatterns = [    
    path("<hashid:pk>/update/", views.UserUpdateView.as_view(), name="user-update"),
                  *******

utils/url.py

class HashIdConverter:
    regex = f'[a-zA-Z0-9]{8,}'

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

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

template

I've tried using

<a href="{% url 'users:user-update' pk=user.hashed_id %}"

also,

<a href="{% url 'users:user-update' user.hashed_id %}"

where hashed_id is as below

def hashed_id(self):
        return h_encode(self.id)

neither of them is working

1

There are 1 best solutions below

1
On BEST ANSWER

You are encoding twice, you should not use hashed_id, since that will hash it again, but:

<a href="{% url 'users:user-update' pk=user.id %}">

The idea of a path-converter is that it will do both the encoding and decoding in a transparent manner.

You should also not use an f string, since that will interpolate the item between curly brackets, so:

class HashIdConverter:
    regex = '[a-zA-Z0-9]{8,}'  # 🖘 no f-string

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

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

Indeed, the f string will determine that you use a tuple, and thus convert this to:

>>> f'[a-zA-Z0-9]{8,}'
'[a-zA-Z0-9](8,)'

this thus means that the regex no longer would use a quantifier like {9,}, but requires an 8 and comma at the end.