gpt4 book ai didi

python - django表单动态选择字段列表选择值

转载 作者:太空宇宙 更新时间:2023-11-03 19:13:25 25 4
gpt4 key购买 nike

问题

我改变我的方法......

我的网址:传递 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')

enter image description here

我点击“提交”,然后:

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 以在查询集对象上选择正确的选择列表

 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. 查询集 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 .

关于python - django表单动态选择字段列表选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12177843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com