Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

python: cannot concatenate 'str' and 'long' objects

I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.

Here's my code:

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")])

for some reason, i always get the following error:

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

The last line is always highlighted.

I'm not trying to concatenate anything. Almost regardless of what I change the list to for the 'choices' parameter, I get this error.

What's going on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Most likely it's highlighting the last line only because you split the statement over multiple lines.

The fix for the actual problem will most likely be changing

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

to

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

As you can quickly test in a Python interpreter, adding a string and a number together doesn'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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...