Django reverse lookup rendering the same (wrong) template
我有一个小的简历网站,当点击反向URL时没有呈现其他模板。
site / scripts / templates / scripts / index.html:
1 2 3 4 5 | <p>were at main</p> python <br/> bash |
这些链接\\'python \\'和\\'bash \\'在URL栏中起作用,它们将我们带到localhost:scripts / bash /和localhost:scripts / python /,但是显示的是完全相同的网页(索引。 html或localhost:scripts /)
site / scripts / urls.py:
1 2 3 4 5 6 7 8 9 | from django.conf.urls import patterns, include, url from scripts import views urlpatterns = patterns('', url(r'$', views.index, name='index'), url(r'python/$', views.access_python, name='python'), url(r'bash/$', views.access_bash, name='bash'), ) |
site / scripts / views.py:
1 2 3 4 5 6 7 8 9 10 | from django.shortcuts import render def index(request): return render(request, 'scripts/index.html') def access_python(request): return render(request, 'scripts/python.html') def access_bash(request): return render(request, 'scripts/bash.html') |
site / urls.py(带有settings.py的主文件夹):
1 2 3 4 5 | from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'scripts/', include('scripts.urls', namespace='scripts')), ) |
单击\\'bash \\'应该检索:
site / scripts / templates / scripts / bash.html:
1 | <p>we're at bash</p> |
为什么反向查询会到达正确的URL,却没有调用该URL模式所需的关联视图?谢谢
索引正则表达式正在捕获任何可能的模式,因为它匹配字符串的任何结尾。我通过将索引模式移到其他2之后发现了它。它应该是:
1 2 3 4 5 6 | urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^python/$', views.access_python, name='python'), url(r'^bash/$', views.access_bash, name='bash'), ) |
任何空白索引url(r'^ $')都需要字符串的开头和结尾,以匹配该模式第一部分之后的空字符串(在这种情况下为'scripts /')