我有一个小的简历网站,在点击反向网址时没有呈现不同的模板。
站点/脚本/模板/脚本/ index.html中:
<p>were at main</p>
<a href="{% url 'scripts:python' %}">python</a>
<br/>
<a href="{% url 'scripts:bash' %}">bash</a>
这些链接'python'和'bash'在URL栏中工作,它们将我们带到localhost:scripts / bash /和localhost:scripts / python /,但显示完全相同的网页(index.html或localhost) :脚本/)
站点/脚本/ urls.py:
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'),
)
站点/脚本/ views.py:
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(主文件夹w / settings.py):
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'scripts/', include('scripts.urls', namespace='scripts')),
)
点击'bash'应检索:
站点/脚本/模板/脚本/ bash.html:
<p>we're at bash</p>
为什么反向查找会到达正确的URL,但是不能调用该URL模式需要的关联视图?谢谢
答案 0 :(得分:3)
索引正则表达式捕获任何可能的模式,因为它匹配字符串的任何一端。我通过在另一个之后移动索引模式找到了它。它应该是:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^python/$', views.access_python, name='python'),
url(r'^bash/$', views.access_bash, name='bash'),
)
任何空白的索引网址(r&#39; ^ $&#39;)都需要字符串的开头和结尾,以匹配该模式的第一部分之后的空字符串(在这种情况下,&#39; scripts / &#39)