模板渲染时出错

时间:2015-06-07 06:49:26

标签: django

我是django的新手,现在关注django教程第4部分(https://docs.djangoproject.com/en/1.8/intro/tutorial04/),我在detail.html中遇到错误。

detail.html

<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.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>

它说,reverse()的错误&#34;参数必须是一个序列&#34; in&#34; {%url&#39;民意调查:投票&#39; question.id%}&#34;。

urls.py

from django.conf.urls import url
from . import views
urlpatterns = {
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
}

views.py

def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

urls.py

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^polls/', include('polls.urls', namespace='polls')),
]

3 个答案:

答案 0 :(得分:1)

您是否定义了民意调查&#39;你的根网址中的命名空间是否正确?

urlpatterns = [
    url(r'^polls/', include('polls.urls', namespace="polls")),
    url(r'^admin/', include(admin.site.urls)),
]

更改此行

return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

return HttpResponseRedirect(reverse('polls:results', kwargs={'pk':p.id}))

答案 1 :(得分:0)

您是否尝试过为您的链接使用命名参数,例如:

{% url 'polls:vote' question_id=question.id %}

或在视图中:

return HttpResponseRedirect(reverse('polls:results', kwargs={'pk': p.pk}))

答案 2 :(得分:0)

在应用程序的urls.py中,

urlpatterns = {...}

应该是

urlpatterns = [...]