官方文档tutorial04 https://docs.djangoproject.com/en/1.10/intro/tutorial04/,会在运行中出现如下错误:
NoReverseMatch at /polls/3/
‘polls’ is not a registered namespace
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/3/
Django Version: 1.9.6
Exception Type: NoReverseMatch
Exception Value:
‘polls’ is not a registered namespace
代码报错会出现(第12行):
10 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
11
12 <form action="{% url 'polls:vote' question.id %}" method="post">
13 {% csrf_token %}
在找了很多方法之后,终于可以了。有两种方法。
(1)在polls.urls中修改(不推荐)
#polls.url 下添加一个app_name就好:
from . import views
app_name = 'polls'
urlpatterns = [...]
(2)在根urls中修改(比如官方文档就是mysite.urls)
加了个namespace
urlpatterns = [
#url(r'^polls/', include('polls.urls')),
#更改成:
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^admin/', admin.site.urls),