Django + Forms: Dynamic choices for ChoiceField

前端 未结 2 788
迷失自我
迷失自我 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:26

    To get deal with the validation on is_valid() action, i think this will work

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

    The code above are untested

提交回复
热议问题