Django + Forms: Dynamic choices for ChoiceField

前端 未结 2 789
迷失自我
迷失自我 2020-12-15 10:36

I\'m trying to create a dynamic list of choices for the ChoiceField but I can\'t seem to call request. Here\'s the code:

The Error:



        
2条回答
  •  执笔经年
    2020-12-15 11:11

    Why not pass the choices in from the view when you instantiate the form?

    e.g.

    Form:

    class FooForm(forms.Form):
        def __init__(self, foo_choices, *args, **kwargs):
            super(FooForm, self).__init__(*args, **kwargs)
            self.fields['foo'].choices = foo_choices
    
        foo = forms.ChoiceField(choices=(), required=True)
    

    View:

    ... 
    bars = request.session['bars']
    foo_list = []
    for bar in bars:
        foo_list.append((bar['id'], bar['name']),)
    form = FooForm(foo_list)
    ...
    

提交回复
热议问题