python:无法连接“str”和“long”对象

2024-05-23 09:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在django设置一个选择字段,但我不认为这是django的问题。choices字段接受2元组的iterable(例如,列表或元组)作为此字段的选项。

这是我的代码:

self.fields['question_' + question.id] = forms.ChoiceField(
                label=question.label,
                help_text=question.description,
                required=question.answer_set.required,
                choices=[("fe", "a feat"), ("faaa", "sfwerwer")])

出于某种原因,我总是会得到以下错误:

TypeError - cannot concatenate 'str' and 'long' objects

最后一行总是高亮显示。

我不想连接任何东西。几乎不管我为'choices'参数将列表更改为什么,我都会得到这个错误。

怎么了?


Tags: django代码selfidfields列表选项错误
3条回答

'question_'是字符串,question.id是长字符串。不能连接两个不同类型的对象,必须使用str(question.id)将long转换为字符串。

可能question.id是一个整数。试试看

self.fields['question_' + str(question.id)] = ...

相反。

很可能是因为您将语句拆分为多行,所以它只突出显示了最后一行。

对实际问题的修正很可能会改变

self.fields['question_' + question.id]

self.fields['question_' + str(question.id)]

由于可以在Python解释器中快速测试,因此将字符串和数字添加在一起不起作用:

>>> 'hi' + 6

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'hi' + 6
TypeError: cannot concatenate 'str' and 'int' objects
>>> 'hi' + str(6)
'hi6'

相关问题 更多 >

    热门问题