django forms Dynamic choicefield list choices value

laurent picture laurent · Aug 29, 2012 · Viewed 7.3k times · Source

Problem

I change my approach...

My url : passing my_code on it

(r'^test_form_2/(?P<my_code>\d+)/$', TestForm_2),

My views : grab the my_code to choose the right choice list on the dic_list

def TestForm_2(request,my_code):

    dic_list = {'1':(('1','A'),('2','B'),('3','C')),
                '2':(('1','D'),('2','E'),('3','F')),
                '3':(('1','G'),('2','H'),('3','I'))
                }

    if request.method =="POST" :
        form = TestForm2(request.POST)

        if form.is_valid():

            return HttpResponse ('OK')

    else :

        my_choices_list = dic_list[my_code]
        form = TestForm2(my_choice=my_choices_list)

    return render_to_response ('zip_finder/page_form.html')

and the form :

class TestForm2(forms.Form):

    my_select = forms.ChoiceField(choices='',label='Choisissez dans la liste')

    def __init__(self, my_choice=None, **kwargs):
        super(TestForm2, self).__init__(**kwargs)
        if my_choice:

            self.fields['my_select'] = forms.ChoiceField(choices=my_choice,label='Choisissez dans la liste')

enter image description here

I click submit and then :

Caught ValueError while rendering: too many values to unpack

I have a look to the HTML and can't see the selected option on my selection :

 <select id="id_my_select" class="select" name="my_select">
<option value="1">D</option>
<option value="2">E</option>
<option value="3">F</option>
</select>

SOLUTION : Use ModelChoiceField

My url : passing my_code on it

  (r'^test_form_2/(?P<my_code>\d+)/$', TestForm_2),

My views : grab the my_code to choose the right choice list on a queryset object

 def TestForm_2(request,my_code):



        if request.method =="POST" :
            form = TestForm2(request.POST)

            form.fields['ville_source'].queryset = Villes.objects.filter(code_postal=my_code)
            if form.is_valid():

                return HttpResponse ('OK')

        else :


            form = TestForm2(my_code=my_code)

        return render_to_response ('zip_finder/page_form.html')

My form :

class TestForm4(forms.Form):


    ville_source = ModelChoiceField(queryset=Villes.objects.all(),required=True,label='Choisissez votre ville source')


    def __init__(self, *args, **kwargs):
        code_postal = kwargs.pop('my_code', None)
        super(TestForm4, self).__init__(*args, **kwargs)

        if code_postal:


            self.fields['ville_source'].queryset = Villes.objects.filter(code_postal=code_postal)

Answer

jpic picture jpic · Aug 29, 2012
  1. Queryset lst_ville is empty, it must be filtering like this, using the unicode value of code_postal:

    .filter(code_postal='<django.forms.fields.CharField object at 0x26bf550>').
    
  2. Use ModelChoiceField instead of CharField:

    # make sure that lst_ville is not an empty queryset
    ville_source = forms.ModelChoiceField(queryset=lst_ville,label='Choisissez votre ville source')
    
  3. For field filtering based on the value of another field of the form, it becomes a little complicated. The simplest solution for you is to just use django-selectables or django-autocomplete-light.