@
click 得确是可以,不过过程有点多, 以下代码仅供参考,请自行调整
1. 定义数据来源, 这里简单的定义一下,如
settings.pyLOCATION = {"浙江": ["杭州", "宁波"], "湖北": ["武汉"]}
2.
models.py COUNTRY = [(key, key) for key in sorted(settings.LOCATION.keys())]
class Company(models.Model):
country = models.CharField(max_length=50, null=True, blank=True, verbose_name=_("Country"), choices=COUNTRY)
state = models.CharField(max_length=50, null=True, blank=True, verbose_name=_('State'))
3.
admin.pyclass CompanyAdminForm(forms.ModelForm):
state = MyChoiceField(label=_('State'), required=False)
def locations(self):
import json
return json.dumps(settings.LOCATION)
def __init__(self, *args, **kwargs):
ins = kwargs.get('instance')
super(CompanyAdminForm, self).__init__(*args, **kwargs)
state = self.fields['state']
if ins and ins.country:
state.choices = [(item, item) for item in settings.LOCATION.get(ins.country)]
class Meta:
model = Company
class CompanyAdmin(admin.ModelAdmin):
form = CompanyAdminForm
4. templates/admin/app/company/change_form.html
复制原change_form.html内容 在合适位置加入(自行写js代码 )
<script type="text/javascript">
var LOCATION = {{ adminform.form.locations | safe }};
var $ = django.jQuery;
$(document).ready(function(){
$('#id_country').change(function(){
var country =$(this).val();
$('#id_state').empty();
if (country ){
var state = LOCATION[country];
var i;
for (i=0; i < state.length; i++){
var v = state[i];
$('#id_state').append("<option value='" + v + "'>" + v + "</option>");
}
} else {
$('#id_state').append("<option value=''>" + "---------" + "</option>");
}
});
});
</script>