首页 > 解决方案 > Django 3.1.3 字段 'id' 需要一个数字,但得到了 '{{ \r\nchoice.id }}'

问题描述

我被困在 Django 的官方教程中(请参阅编写你的第一个 Django 应用程序,第 4 部分)。 https://docs.djangoproject.com/en/3.1/intro/tutorial04/

我收到以下错误:

https://i.stack.imgur.com/7zPI9.png

在这个 Django 项目中,在我正在制作的投票应用程序中,我们应该在 views.py 中创建一个 vote() 视图,它应该处理投票的 POST 请求数据并将我们重定向到 results() 视图(有投票()视图没有模板,它只是负责处理我们通过投票发送的数据)。起初我以为我有一个拼写错误,但后来我直接从文档教程(我在这个问题的开头链接)复制粘贴了所有内容,并且错误仍然存​​在。

视图.py

from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.shortcuts import get_object_or_404, render
from django.template import loader
from django.urls import reverse
from .models import Choice, Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)


def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        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 an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

网址.py

from django.urls import path
from . import views

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

结果.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>

索引.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 %}

细节.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>

如果这对任何人都有帮助

Traceback (most recent call last):
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Danny\Python\Poll\mysite\polls\views.py", line 41, in vote
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, *args, **kwargs)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 
1358, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 
1377, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 
1319, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 
1165, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "C:\Users\Danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1776, in get_prep_value
    raise e.__class__(
ValueError: Field 'id' expected a number but got '{{ \r\nchoice.id }}'.

标签: python-3.xdjango

解决方案


由于某种原因,django 使用 int: question_id 作为字符串进行重定向,您可以添加您的 urls 文件吗?


推荐阅读