Django + Forms: Dynamic Choice for ChoiceField

I am trying to create a dynamic list of options for ChoiceField, but I cannot request a request. Here is the code:

Error:

AttributeError: 'CreationForm' object has no attribute 'request' 

Forms

 class FooForm(forms.Form): def __init__(self, *args, **kwargs): super(FooForm, self).__init__(*args, **kwargs) bars = self.request.session['bars'] foo_list = [] for bar in bars: foo_list.append((bar['id'], bar['name']),) self.fields['foo'].choices = foo_list foo = forms.ChoiceField(choices=foo_list, required=True) 
+6
source share
2 answers

Why not pass the selection from the view when you instantiate the form?

eg.

the 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) ... 
+16
source

To access the validation in the 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) 

Code above not verified

0
source

All Articles