20

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?

1
  • Note that "the last line is highlighted" because it's pointing to the whole multi-line statement in which the error is located. Commented Aug 20, 2010 at 16:34

5 Answers 5

36

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'
Sign up to request clarification or add additional context in comments.

Comments

6

'question_' is a string, question.id is a long. You can not concatenate two things of different types, you will have to convert the long to a string using str(question.id).

Comments

2

Probably question.id is an integer. Try

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

instead.

Comments

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

That looks like the problem. Try

"question_%f"%question.id

or

"question_"+ str(question.id)

Comments

-2

This is a problem with doing too many things in one line - the error messages become slightly less helpful. Had you written it as below the problem would be much easier to find

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.