Django:模板url标签错误的目标

时间:2017-09-06 19:51:50

标签: python django url

我的主要网址是:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('scoring.urls', namespace='scoring')),
]

并在我的应用网址中:

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

并在我的模板中:

<li><a href="{% url 'scoring:index' %}">Scoring</a></li>

{% url 'scoring:index' %}生成的内容为localhost/而不是localhost/scoring。为什么呢?

1 个答案:

答案 0 :(得分:2)

首先,您可以在主^scoring文件中添加urls.py前缀,而不是在评分网址中随处写入:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^scoring/', include('scoring.urls', namespace='scoring')),
]

然后在得分urls.py中确保添加app_name

app_name = 'scoring'

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

(请注意,我删除了网址格式中的scoring前缀。)

现在,当您添加app_name时,模板中的反转应该按预期工作。