Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django + Forms: Dynamic choices for ChoiceField

Tags:

forms

django

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:

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)
like image 216
user1909186 Avatar asked Mar 07 '14 16:03

user1909186


2 Answers

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)
...
like image 150
chewynougat Avatar answered Nov 13 '22 06:11

chewynougat


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

like image 1
Aditya Kresna Permana Avatar answered Nov 13 '22 07:11

Aditya Kresna Permana