使用自定義 url 轉換器時出現此錯誤
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']
問題:為什么 pk 與正則運算式不匹配,下面給出了錯誤的詳細資訊
網址.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"),
*******
實用程式/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)
模板
我試過使用
<a href="{% url 'users:user-update' pk=user.hashed_id %}"
還,
<a href="{% url 'users:user-update' user.hashed_id %}"
其中 hashed_id 如下
def hashed_id(self):
return h_encode(self.id)
他們都沒有作業
uj5u.com熱心網友回復:
您正在編碼兩次,您不應該使用hashed_id,因為這將再次對其進行哈希處理,但是:
<a href="{% url 'users:user-update' pk=user .id %}">
路徑轉換器的想法是它將以透明的方式進行編碼和解碼。
您也不應該使用字串f,因為這會在大括號之間插入專案,因此:
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)
實際上,f字串將確定您使用元組,因此將其轉換為:
>>> f'[a-zA-Z0-9]{8,}'
'[a-zA-Z0-9](8,)'
因此,這意味著正則運算式不再使用量詞 like {9,},而是8在末尾需要一個和逗號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/529751.html
