【问题标题】:Reverse for 'tagged' with arguments '('',)' not found. 1 pattern(s) tried: ['^tag/(?P<slug>[-\w]+)/$']未找到带有参数 '('',)' 的 'tagged' 的反向操作。尝试了 1 种模式:['^tag/(?P<slug>[-\w]+)/$']
【发布时间】:2021-12-20 12:07:10
【问题描述】:

我不断收到此错误消息:

未找到带有参数 '('',)' 的 'tagged' 的反向操作。尝试了 1 种模式:['\^tag/\(\?P(?P[^/]+)\[\-\\w\]\+\)/\$$']

在尝试加载我的 base.html 时,由于锚标记。 我看过其他有相同问题的帖子,但我仍然不知道我哪里出错了。

views.py

class TagIndexView(TagMixin, ListView):
    template_name = 'post/index.html'
    model = Post
    paginate_by = '10'
    context_object_name = 'posts'

    def get_queryset(self):
        return Post.objects.filter(tags__slug=self.kwargs.get('slug'))

def tagged(request):
    return render(request, 'blog/tagged.html', {'title': 'Tagged'})

urls.py

path(r'^tag/(?P<slug>[-\w]+)/$',TagIndexView.as_view, name='tagged')

base.html
锚标记:

<li class="list-group-item"><a href="{% url 'tagged' tag.slug %}">Tags</a></li>

但我不断收到 NoReverseMatch。在锚标签中,我尝试了“tag.slug”、“tag.id”、“tag.pk”等。

【问题讨论】:

  • 会不会是因为你没有在as_view后面加括号? TagIndexView.as_view()
  • 这是您的 href 中 tag.slug 为空时的典型错误消息。检查您传递给 html 的内容。
  • 我只是把括号放在 as_view 之后,但我仍然得到同样的错误。感谢您指出这一点。
  • [-\w]+ -> [-\w]*?
  • 没用。不过谢谢。

标签: django django-urls django-url-reverse


【解决方案1】:
  1. 对正则表达式使用re_path() 而不是path()。

    参考:https://docs.djangoproject.com/en/3.2/topics/http/urls/#using-regular-expressions

  2. 使用[-\w]*(0 或更多)而不是[-\w]+(1 或更多)来允许空字符串('',)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多