开发者

Django: provide choices list to a checkbox from a view function

开发者 https://www.devze.com 2022-12-12 02:44 出处:网络
in my Django application I\'ve got a form with a ChoiceField that normally allows to choice between a range of integer values.

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 arg开发者_运维百科ument '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 :)


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) 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消