简体   繁体   中英

Django form ChoiceField depend on another ChoiceField

I have the following form:

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)

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?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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