我是 Django 的新手。 让 Django 1.4.2 与 Python 2.7 一起工作 在 Windows 7 上。
我正在学习教程,我需要显示一个表单模板 与单选按钮。选择一个按钮发送数据,页面应该 问您是否想“再次投票?”。另外,如果您不选择按钮 并提交表单,它应该显示一条消息,要求您做出选择。
到目前为止, 这是 HTML 表单:
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
现在,当我输入 http://localhost:8000/polls/1/
时,我应该得到表单,但我收到以下错误消息:
NoReverseMatch at /polls/1/
u"'polls" is not a registered namespace
我将 polls 注册为命名空间,请参阅下面的项目 urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
为了回答 Cathy 的善意请求,以下是投票网址:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
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'),
)
..如果有帮助的话,我在下面包含了项目文件夹的网址:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)
我刚刚注意到浏览器上显示以下错误消息(因为 Debug = True):
Error during template rendering
In template C:\Python27\Scripts\mysite\mytemplates\polls\index.html, error at line 4
u"'polls" is not a registered namespace
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
任何使该表单正常运行的帮助将不胜感激!
最佳答案
urlpatterns = patterns('polls.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'),
)
{% url polls:detail poll.id %}
关于Django - 如何运行表单模板(获取 ' namespace not registered error ' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14791705/