gpt4 book ai didi

python - Django "remove hardcoded urls in templates"不工作

转载 作者:行者123 更新时间:2023-11-30 23:20:21 24 4
gpt4 key购买 nike

我是按照教程第一次查看 django https://docs.djangoproject.com/en/1.6/intro/tutorial03/

到目前为止,一切都很顺利。我在“删除硬编码的网址”部分遇到了障碍。我正在使用 Django 1.6.6。

当我更改硬编码网址时:

<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

至:

<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>

我收到如下 404 错误:

Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/polls/%7B%%20url%20'detail'%20poll.id%20%7D

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

^polls/ ^$ [name='index']
^polls/ ^(?P<poll_id>\d+)/$ [name='detail']
^polls/ ^(?P<poll_id>\d+)/results/$ [name='results']
^polls/ ^(?P<poll_id>\d+)/vote/$ [name='vote']
^admin/

The current URL, polls/{% url 'detail' poll.id }, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

地址栏中显示的网址是

mylocalenv/polls/%7B%%20url%20%27detail%27%20poll.id%20%7D

我尝试删除“detail”中的引号,但考虑到我使用的是 django 1.6.6,我不需要这样做。它也不起作用。我也尝试过跳过一点,将/polls/命名空间包含在 urls.py 中,但同样没有什么乐趣。

我的 urls.py 文件如下所示:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),

)

我的index.html模板中的确切代码是:

{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}

明白了

但令人沮丧的是我不知道为什么。出于对index.html的绝望,我开始在这一行上使用index.html文件:

<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>

没有任何逻辑原因,我将 poll.id 更改为 poll_id。正如我所料,重新加载破坏了index.html。当我将其改回 poll.id 时,一切正常。这毫无意义。我什至按 ctrl^z 返回到以前不起作用的 index.html,现在它也起作用了。我在每次检查之前都重新启动了服务器。我很烦。但至少它正在发挥作用。

最佳答案

回溯中的这一行表明您错过了右大括号之前的 %

The current URL, polls/{% url 'detail' poll.id }, didn't match any of these.

关于python - Django "remove hardcoded urls in templates"不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25555344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com