7
from django import forms

class SignUpForm(forms.Form):
    birth_day = forms.ChoiceField(choices=range(1,32))

I'm getting "Caught TypeError while rendering: 'int' object is not iterable". https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices says the choices argument takes iterables such as a list or tuple.

http://docs.python.org/library/functions.html#range says range() creates a list.

Why am I getting an error?

I tried converting the list to str using map() but received different errors.

deadghost
  • 5,017
  • 3
  • 34
  • 46

2 Answers2

18

... says the choices argument takes iterables such as a list or tuple.

No, it says it takes an iterable of 2-tuples.

An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.

birth_day = forms.ChoiceField(choices=((str(x), x) for x in range(1,32)))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    Works, looks like I need to be careful when reading. Solution has one extra left parentheses that needs to be removed. – deadghost Nov 06 '11 at 05:45
  • @IgnacioVazquez-Abrams: is there any reason why you use generator instead list or tuple? http://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python – noisy Aug 19 '14 at 21:24
  • @noisy: Mostly force of habit, but there's no need for the full data structure in the bytecode. – Ignacio Vazquez-Abrams Aug 19 '14 at 21:32
0

You need 2 tuples. Use zip built-in function for the same 2 tuples

from django import forms


class SignUpForm(forms.Form):

    birth_day = models.IntegerField(choices=list(zip(range(1, 32), range(1, 32))), unique=True)

Remember (1,32) will create from 1 to 31 !

Pablo Ruiz Ruiz
  • 605
  • 1
  • 6
  • 23