您可能需要使用以下技术:
- 自定义 Django 表单字段(在模型表单中)
- ajax(获取记录)
- simplejson(向 ajax 发送 json 响应)
- jquery(更新客户端的组合框)
让我们看一个例子(没有真正测试过,只是从我的脑海中):
模型.py
from django.db import models
class Campus(models.Model):
name = models.CharField(max_length=100, choices=choices.CAMPUSES)
def __unicode__(self):
return u'%s' % self.name
class School(models.Model):
name = models.CharField(max_length=100)
campus = models.ForeignKey(Campus)
def __unicode__(self):
return u'%s' % self.name
class Centre(models.Model):
name = models.CharField(max_length=100)
school = models.ForeignKey(School)
def __unicode__(self):
return u'%s' % self.name
表格.py
import models
from django import forms
class CenterForm(forms.ModelForm):
campus = forms.ModelChoiceField(queryset=models.Campus.objects.all())
school = forms.ModelChoiceField(queryset=models.School.objects.none()) # Need to populate this using jquery
centre = forms.ModelChoiceField(queryset=models.Centre.objects.none()) # Need to populate this using jquery
class Meta:
model = models.Center
fields = ('campus', 'school', 'centre')
现在,在您的视图中编写一个方法,该方法为校园下的学校和学校下的中心返回一个 json 对象:
视图.py
import models
import simplejson
from django.http import HttpResponse
def get_schools(request, campus_id):
campus = models.Campus.objects.get(pk=campus_id)
schools = models.School.objects.filter(campus=campus)
school_dict = {}
for school in schools:
school_dict[school.id] = school.name
return HttpResponse(simplejson.dumps(school_dict), mimetype="application/json")
def get_centres(request, school_id):
school = models.School.objects.get(pk=school_id)
centres = models.Centre.objects.filter(school=school)
centre_dict = {}
for centre in centres:
centre_dict[centre.id] = centre.name
return HttpResponse(simplejson.dumps(centre_dict), mimetype="application/json")
现在编写一个 ajax/jquery 方法来获取数据并填充select
HTML 中的元素。
AJAX/jQuery
$(document).ready(function(){
$('select[name=campus]').change(function(){
campus_id = $(this).val();
request_url = '/get_schools/' + campus_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(index, text){
$('select[name=school]').append(
$('<option></option>').val(index).html(text)
);
});
}
});
return false;
})
});