Django表单ChoiceField依赖于另一个ChoiceField [英] Django form ChoiceField depend on another ChoiceField

查看:168
本文介绍了Django表单ChoiceField依赖于另一个ChoiceField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式:

class MyForm(forms.Form):
    country = forms.ChoiceField(
        widget = forms.Select()
    )

    region = forms.CharField(
        widget = forms.Select()
    )

    def update_region(self):
        self['region'].field.widget.choices = get_choices_for_region(
            self['region'].field.initial)

区域选择取决于国家/地区的选择。我有一个ajax例程来更新所选国家的地区。我在该地区使用了一个CharField,所以它将正确验证。

The region choices depend on the country choices. I have an ajax routine to update the region with the selected country. I used a CharField for the region so it will validate properly.

实际上,我用视图内的数据预先填写表单:

Actually I prepopulate the form with data inside my view:

myform['country'].field.initial = 'Switzerland'
myform.update_region()
return ...

问题:有没有办法强制区域选择自动更新国家?

Question: Is there a way to force the region choices to update automatically with updating the country?

推荐答案

我最近碰巧面临类似的问题(并且浪费了更多的时间在这个比想要的)。为了使过程快速,我首先在页面加载时在视图中创建了国家/地区列表。然后,在Jquery Magic的帮助下,您可以根据所选的国家/地区字段动态设置区域。

I recently happened to face similar issue (and wasted a lot more time on this than would have liked). To make the process fast, I first created Country-Region Lists in the view at the time of page loading. Then, with the help of little Jquery Magic you can dynamically set the fields of region based on the country field chosen.

此外,还有一个简单的实现在这个链接中。

Also here is a simple implementation of what you are looking for in this link.

还有一个更好的替代每次国家的字段(要获取所选国家/地区的dict的列表,让我们称之为region_for_country)进行AJAX调用更改为更新区域选项。在Jquery中查找作为作业一部分的以下代码片段。

Also there is a even better alternative to make a AJAX call every time the country's field(to get a list of dict of regions for the selected country, let's call it regions_for_country) is changed to update the regions options. Find the following snippet in Jquery that does part of the job.

var html = $.map(regions_for_country, function(item){
        return '<option value="' + item['key'] + '">' + item['value'] + '</option>'
    }).join('');

这将为您可以轻松替换的选项生成html代码,方法是使用 .html()命令。我更喜欢上一种方法,就像以前的方法一样,我们浪费时间生成国家/地区的关键价值对,这可能对大数据集有害。

This will generate the html code for the options which u can replace easily by using the .html() command. I would prefer the last method as in the previous method we are wasting time generating the key value pairs of country-region, which can be detrimental for big datasets.

这篇关于Django表单ChoiceField依赖于另一个ChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆