我有一个 Django 站点,可以在其中单击帖子的标签(我使用 tagulous)来查看使用该标签的所有帖子的列表。它工作正常,除非字符串是 unicode。具体来说,是我的模板的这一行给我一个错误:
<a href="{% url 'fortykwords:tag' tag.name %}">{{ tag.name }}</a>
它给了我错误
Reverse for 'tag' with arguments '('你好',)' not found. 1 pattern(s) tried: ['tag\\/(?P<input_tag>[-a-zA-Z0-9_]+)$']
这是 urls.py:
path('tag/<slug:input_tag>', views.tag_view, name='tag'),
这是来自 views.py 的 View :
def tag_view(request, input_tag):
latest_post_list = Post.objects.filter(tags=input_tag,
status__exact="published")
context = {'latest_post_list': latest_post_list, 'page_tag': input_tag}
return render(request, 'fortykwords/tag.html', context)
我应该更改什么以便可以使用 unicode 参数反向链接?
最佳答案
尝试使用模式 \w+
而不是 [-a-zA-Z0-9_]+
。
为此,您需要将 path
更改为 re_path
以对 url 使用您自己的自定义正则表达式。
示例:
from django.urls import path, re_path
urlpatterns = [
# your regular paths
path('...'),
# update to `re_path` for those which can accept unicode letters
url(r'tag/(?P<input_tag>\w+)$', views.tag_view, name='tag'),
]
关于python - 在参数中使用带有 unicode 字符的 {% url %} 反向 (Django),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51677078/