【问题标题】:django does not match pattern called in templatedjango 与模板中调用的模式不匹配
【发布时间】:2015-07-04 20:02:53
【问题描述】:

我试图在模板中调用{% url %} 以获得动态链接,但我得到一个错误,尽管模式应该匹配。这是我的文件:

urls.py

urlpatterns = [
    url(r'^(?P<team_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^$', views.index, name='index'),
]

模板文件

{% for team in teams_list %}
            <li><a href="{% url 'detail' team.id %}/">{{ team.name }}</a></li>
        {% endfor %}

views.py

def detail(request, team_id):
    team = get_object_or_404(Team, id=team_id)
    context = {
        'teamname' : team.name,
        'member_list' : User.objects.filter(team__name=team.name)
    }
    return render(request, 'teams/detail.html', context)

我尝试过模拟 django 教程,但我似乎找不到我的错误。错误说明如下:

Reverse for 'detail' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

【问题讨论】:

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


    【解决方案1】:

    线索在错误消息中,特别是找不到关键字参数“{}”。

    您的模式具有关键字匹配,结果将映射到关键字team_id,但是您传递的是1位置参数(这就是您的团队ID 显示在元组中的原因(1,))。

    要解决此问题,请将您的 url 标签更改为 {% url 'detail' team_id=team.id %}

    您可以在url tag documentation 上阅读更多相关信息。

    【讨论】:

    • 非常感谢,感谢您的帮助和进一步的资源。
    • 当模式有关键字参数时,我从来没有遇到过向reverse 提供参数元组的任何问题。 0 pattern(s) tried 在我看来更可疑。
    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多