python:无法连接'str'和'long'对象
问题描述:
我试图在django中设置一个选择字段,但我不认为这是一个Django问题。选择字段采用2元组的可迭代(例如,列表或元组)作为该字段的选项。python:无法连接'str'和'long'对象
这里是我的代码:
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
最后一行总是高亮显示。
我不想连接任何东西。几乎不管我改变列表的'选择'参数,我得到这个错误。
发生了什么事?
答
最有可能的是它突出显示最后一行,只是因为您将语句拆分为多行。
为实际问题的修补程序将最有可能被改变
self.fields['question_' + question.id]
到
self.fields['question_' + str(question.id)]
正如你可以在Python解释器快速测试,增加一个字符串和一个数字一起没有按't work:
>>> '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'
答
可能question.id
是一个整数。尝试
self.fields['question_' + str(question.id)] = ...
改为。
答
'question_'
是一个字符串,question.id
是一个长。你不能连接两种不同类型的东西,你必须使用str(question.id)
将long转换为一个字符串。
答
self.fields['question_' + question.id]
看起来像这个问题。尝试
"question_%f"%question.id
或
"question_"+ str(question.id)
答
这是一条线中做太多的事情一个问题 - 错误信息变得稍显不足很有帮助。如果你把它写成如下,问题就会容易得多
question_id = 'question_' + question.id
self.fields[question_id] = forms.ChoiceField(
label=question.label,
help_text=question.description,
required=question.answer_set.required,
choices=[("fe", "a feat"), ("faaa", "sfwerwer")])
请注意,“最后一行是突出显示的”,因为它指向错误所在的整个多行语句。 – 2010-08-20 16:34:28
非常感谢大家。那解决了它。 – Roger 2010-08-20 16:51:57