我是 Django 的新手。让 Django 1.4.2 在 Windows 7 上与 Python 2.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)),
)
为了回答凯茜的好心请求,这里是投票网址:
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 %}
任何帮助使该表格正常运行将不胜感激!