繁体   English   中英

django表单动态choicefield列表选择值

[英]django forms Dynamic choicefield list choices value

问题

我改变了方式...

我的网址:在上面传递my_code

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

我的观点:抓取my_code以在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')

以及形式:

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')

在此处输入图片说明

我单击提交,然后:

Caught ValueError while rendering: too many values to unpack

我看了看HTML,看不到所选内容中的所选选项:

 <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>

解决方案:使用ModelChoiceField

我的网址:在上面传递my_code

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

我的观点:获取my_code以在queryset对象上选择正确的选择列表

 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')

我的表格:

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)
  1. Queryset lst_ville为空 ,必须使用code_postal的unicode值像这样进行过滤:

     .filter(code_postal='<django.forms.fields.CharField object at 0x26bf550>'). 
  2. 使用ModelChoiceField代替CharField:

     # make sure that lst_ville is not an empty queryset ville_source = forms.ModelChoiceField(queryset=lst_ville,label='Choisissez votre ville source') 
  3. 对于基于表单的另一个字段的值进行字段过滤 ,这变得有些复杂。 最简单的解决方案是只使用django-selectablesdjango-autocomplete-light

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM