views:

403

answers:

2

Hi, in my Django application I've got a form with a ChoiceField that normally allows to choice between a range of integer values.

class FormNumber(forms.Form):
list=[]
for i in range(1, 11):
 list.append((i,i))
number=forms.ChoiceField(choices=list, initial=1)

Now I need to override the default choices list from a view method in some cases, using a smaller range, but trying to do it in this way

n=10-len(request.session["items"])
 if n>0:
  list=[]
  for i in range(1, n+1):
   list.append((i,i))
  form=FormNumber(choices={'number':list}, initial={'number':1})

I get a TypeError - __ init__() got an unexpected keyword argument 'choices'. I tried also to remove the parameters from the form class, but I get the same result.

Is there a way to initialize the ChoiceField with a new choices list from the view in a way similar to the one above? Thanks in advance :)

+1  A: 

I would add an __init__(choices=None) function to the form class FormNumber and initialize the ChoiceField number using that unless it's None.
If choices is not provided (defaults to None), initialization would do what it does by default.

Niklas
Thanks for your reply, I'm trying to solve in this way, let's see what happens
Alex
It worked, thanks again Niklas!
Alex
A: 

I post the code, maybe someone in future needs to solve a similar problem.

The form code now is this one:

class FormNumber(forms.Form): 
    def __init__(self, list=None, *args, **kwargs):
        super(FormNumber, self).__init__(*args, **kwargs)
        self.fields["number"]=forms.ChoiceField(choices=list)

and I call it from the view simply with

form=FormNumber(list=number_list)
Alex