【问题标题】:Django 3.1.3 Field 'id' expected a number but got '{{ \r\nchoice.id }}'Django 3.1.3 字段 'id' 需要一个数字,但得到了 '{{ \r\nchoice.id }}'
【发布时间】:2021-03-13 14:53:19
【问题描述】:

我被 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()视图(vote() 视图没有模板,它只是负责处理我们通过投票发送的数据)。起初我以为我有一个拼写错误,但后来我直接从文档教程(我在这个问题的开头链接)复制粘贴了所有内容,并且错误仍然存​​在。

views.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,)))

urls.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 }}'.

【问题讨论】:

  • 能重新粘贴一下图片吗?它没有通过。我没有在您的代码中看到您的 {{choice.id }} 发挥作用,所以也许它在图像中。
  • 对不起,在这里发布问题还是新手。感谢您的耐心。
  • @keepAlive 错误依旧。
  • 你能试试下一个吗:reverse('polls:results',kwargs={'question_id': question.id}) 取自stackoverflow.com/questions/58107188/…
  • @RamsésMartínezOrtiz 它仍然给我同样的错误。我可能不得不结束这个项目。它可能比这个项目更深层次,因为它在异常中声明 query.py 和 lookups.py,这不是项目创建的一部分。

标签: python-3.x django


【解决方案1】:

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

【讨论】:

  • 我刚刚编辑了帖子及其在views.py下的内容
【解决方案2】:

我在学习教程第 4 部分时遇到了同样的错误。

Error: Field 'id' expected a number but got '{{ \r\nchoice.id }}'
the error is "\r\n" before the choice.id

detail.html中,这里应该没有回车。

value="{{ choice.id }}"

去掉choice.id之前的回车,然后刷新网页。不应该是错误。

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2021-06-03
    • 2021-01-22
    • 2021-07-30
    相关资源
    最近更新 更多