python - Django TypeError at/polls/1/vote/_reverse_with_prefix() * 之后的参数必须是可迭代的,而不是 int

标签 python django django-forms django-templates django-views

这是 Django Docs 的民意调查应用程序教程。

当我转到第一个问题http://127.0.0.1:8000/polls/1/时,选择一个选项并单击“投票”,我收到错误消息。

error message

views.py:

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        # request.POST['choice'] returns ID of the selected choice as a string
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return a HttpResponseRedirect after successfully dealing with POST data.
        # This prevents the data from being posted twice if a user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=question_id, ))

民意调查/urls.py:

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

民意调查/模板/民意调查/index.html:

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

民意调查/模板/民意调查/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>

民意调查/模板/民意调查/results.html:

<h1>{{ question.question_text }}</h1>

<ul>
    {% for choice in question.choice_set.all %}
        <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
    {% endfor %}
</ul>

<a href="{% url 'polls:detail' question.id %}">Vote again?</a>

有人可以帮忙吗?

最佳答案

问题是你写的是:

    return HttpResponseRedirect(reverse('polls:results', <b>args=question_id</b>, ))

现在args用于位置参数,并且(理论上)可以有多个。所以它应该是一个项目的集合。例如:

    return HttpResponseRedirect(reverse('polls:results', args=<b>[</b>question_id<b>]</b>, ))

Note: in the tutorial they write args=(question_id,). Now that is something different than args=question_id. In Python a (0, ) is not an integer, but a 1-tuple containing one element: 0. In short: the brackets matter.

但是没有必要进行所有这些包装。 Django 有一个快捷方式 redirect(…) [Django-doc] ,以更方便的方式构建 HttpResponseRedirect:

    return <b>redirect(</b>'polls:results', question_id<b>)</b>

这将 *args**kwargs 本身作为位置参数和命名参数。所以你可以像直接调用 View 一样编写它( View 的名称在前面)。

关于python - Django TypeError at/polls/1/vote/_reverse_with_prefix() * 之后的参数必须是可迭代的,而不是 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51559298/

相关文章:

python - 使用 Pinax 的最大好处是什么?

python - 未调用 CreateView 中的 Django form_valid() 和 form_invalid()

python - pygame全屏模式退出

javascript - 设置 URL 以在 Django 模板中加载 iframe

javascript - 一个 django 表单,有两个输入、两个 url、两个 View ,下一页都有不同的 js

django - 使用Django在我的模板库中显示一个表单

django - 内联表单集工厂 - 将请求传递给子表单

python - 如何打开带有递增数字的文件?

python - 在 Pandas 中将 csv 转换为 txt 时,电话号码中丢失 "+"

python - OSError : [WinError 123] The filename, 目录名或卷标语法不正确