我设计了这个投票应用程序,我正在尝试将硬代码 url 转换为命名空间 url,但路径上有错误。
这是我的 index.html,你可以看到他们的硬编码 url 指向我的 URLconf。
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
我的 myapp URLconf。
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name="index"),
url(r'^(?P<poll_id>\d+)/$', 'detail',name="detail"),
url(r'^(?P<poll_id>\d+)/results/$', 'results', name="results"),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote', name="vote"),
)
这是我的主要 URLconf。
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('myapp.urls', namespace='myapp')),
,
)
我的观点是:
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/detail.html', {'poll': p},
context_instance=RequestContext(request))
我试图用 {% url detail poll.id %} 或 {% url myapp:detail poll.id %} 替换硬编码错误
但我收到了这个错误
NoReverseMatch at /polls/
Reverse for 'detail' with arguments '(5,)' and keyword arguments '{}' not found.
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Django Version: 1.4.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'detail' with arguments '(5,)' and keyword arguments '{}' not found.
Error during template rendering
In template C:\djcode\mysite\myapp\templates\myapp\index.html, error at line 4
Reverse for 'detail' with arguments '(5,)' and keyword arguments '{}' not found.
1 {% if latest_poll_list %}
2 <ul>
3 {% for poll in latest_poll_list %}
4 <li><a href="{% url detail poll.id %}">{{ poll.question }}</a></li>
5 {% endfor %}
6 </ul>
7 {% else %}
8 <p>No polls are available.</p>
9 {% endif %}
如何将此硬编码的 URL 转换为命名空间,以便它可以指向 myapp URLconf 而不会出现任何错误?