34👍
✅
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)
...
1👍
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
- Reverse Queryset Order in Django
- Django database delete specific number of entries
- How to unit test methods inside django's class based views?
- Django reverse error: NoReverseMatch
- Using existing field values in django update query
Source:stackexchange.com