【问题标题】:NoReverseMatch - Simple Django forums applicationNoReverseMatch - 简单的 Django 论坛应用程序
【发布时间】:2014-02-18 15:24:48
【问题描述】:

我正在尝试创建一个简单的论坛应用程序并收到此错误。我倾向于认为这可能与我的 URLConf 或我使用 URL 模板标记为每个线程生成 URL 的方式有关。

/forums/urls.py

# ex: /forums/general_forum
url(r'^(?P<forum_slug>[-\w\d]+)/$', views.forum, name='forum'),

# ex: /forums/general_forum-1/my_first_thread
url(r'^(?P<forum_slug>[-\w\d]+)/(?P<thread_slug>[-\w\d]+)/$', views.thread, name='thread'),

/forums/views.py

index 视图工作正常,论坛 视图却不行。

def index(request):
    context = RequestContext(request)
    forum_list = Forum.objects.order_by("sequence")

    for forum in forum_list:
        forum.url = slugify(forum.title) + "-" + str(forum.id)

    context_dict = {'forum_list': forum_list}
    return render_to_response('forums/index.html', context_dict, context)

@login_required
def forum(request, forum_slug):
    context = RequestContext(request)

    try:
        forum = Forum.objects.get(slug=forum_slug)

        threads = Thread.objects.filter(forum=forum)

        context_dict = {'forum': forum,
                        'threads': threads}

    except Forum.DoesNotExist:
        pass

    return render_to_response('forums/forum.html', context_dict, context)

这就是我在 index.html 中链接到 forum 视图的方式。

<a href={% url 'forum' forum.slug %}>{{ forum.title }}</a>

在forum.html 中,这就是链接用于查看线程内帖子的方式。这个:

<a href={% url 'forum' forum.slug %}/{% url 'thread' thread.slug %}>{{ thread.title }}</a>

错误。其中一个主题的标题是“django”

NoReverseMatch at /forums/web-development/

Reverse for 'thread' with arguments '(u'django',)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['forums/(?P<forum_slug>[-\\w\\d]+)/(?P<thread_slug>[-\\w\\d]+)/$', '$(?P<forum_slug>[-\\w\\d]+)/(?P<thread_slug>[-\\w\\d]+)/$']

在错误中,'thread' 的 url 模板标记以红色突出显示,并指​​出在模板呈现期间出现错误。这个错误对我来说似乎不清楚,我不确定这是否是我使用模板标签或其他方式的问题。

【问题讨论】:

    标签: python django django-templates django-views django-urls


    【解决方案1】:

    您没有在您的主题 URL 中传递论坛 slug,这是您的 URL 配置所需的:

    <a href={% url 'forum' forum.slug %}/{% url 'thread' thread.slug %}>{{ thread.title }}</a>
    

    您也不应该同时使用这两个网址。相反,你想要的是:

    <a href="{% url 'thread' forum.slug thread.slug %}">{{ thread.title }}</a>
    

    【讨论】:

    • 嗯,这很简单(我以为我已经尝试过了)。现在我觉得很傻!非常感谢:)
    猜你喜欢
    • 2015-09-19
    • 2020-02-09
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2013-10-16
    • 2022-01-20
    相关资源
    最近更新 更多