【问题标题】:(can only concatenate str (not "int") to str) this is the error i am getting why is it saying that i am trying to add string and int?(只能将str(不是“int”)连接到str)这是我得到的错误为什么它说我正在尝试添加字符串和int?
【发布时间】:2020-05-08 11:12:43
【问题描述】:

我正在关注 django 官方文档教程 t 制作投票应用程序我目前卡在第 4 部分。因此,当我选择其中一个选项时,它会显示错误(只能将 str(而不是“int”)连接到字符串)。 我不明白我是否试图将字符串添加到整数中,代码中的问题在哪里

请帮助这是我的代码:

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
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):
    question = get_object_or_404(Question, pk=question_id)
    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'),
]

models.py

import datetime
from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=250)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

【问题讨论】:

  • 哪一行导致错误?
  • views.py 的第 35 行,上面写着 selected_choice.votes += 1
  • Django 的回溯包括每个级别的“本地变量”部分,展开该部分,您可以准确地看到 selected_choice 包含的内容。
  • 它显示 selected_choice 但我想增加 1 到 selected_choice.votes

标签: python django


【解决方案1】:

要进行故障排除,您可以删除串联并在整个代码中插入 print(type(variable_name)) 以打印变量类型,以查看 python 将 string 类型分配给变量的位置。

包含完整的错误消息将有助于任何其他故障排除。

看起来 django 不会将值强制为整数,所以我怀疑这就是你的问题所在。 votes = models.IntegerField(default=0) 来自您的 models.py。这里有一个相关的问题,它也建议进行类似于我建议的故障排除。然后将该值显式转换为整数。 Django IntegerField returning string(!) - how to coerce to int?

【讨论】:

  • 我不能这样做,因为我正在增加查看 views.py 的第 35 行,上面写着 selected_choice.votes += 1 这就是问题的根源
  • 是的,这就是问题的根源。删除 += 1 以避免错误并打印变量的类型以查看它在哪里被分配了 string 类型。
  • @Naveednaseer 我更新了我的答案。请参阅附加信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-06
  • 2022-06-11
  • 1970-01-01
相关资源
最近更新 更多