我是django和jquery的新手。我正在开发一个基于django的应用程序,其中我在一个表单中有3个下拉列表。1.校园2.学校3.中心
等级制度是校园有学校,学校有中心。我想将这些下拉列表链接起来。
例如,我有3个校区,分别是Campus1,Campus2,Campus3。如果我选择Campus1,我应该只能在campus1中选择学校,如果我选择School1,那么我需要能够选择School1的中心,所有其他选项都应该隐藏。
我在网上搜索并尝试了这个http://blog.devinterface.com/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/,但它似乎对我不起作用。我也检查过这个http://www.javascriptkit.com/script/script2/triplecombo.shtml,但是因为我使用ModelForm来创建表单,所以这不符合我的需要。
请指导我这样做。
谢谢
发布于 2013-01-02 20:28:07
您可能需要使用以下技术:
让我们来看一个例子(没有真正测试过,只是在我的脑海中):
Models.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.nameForms.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对象:
Views.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方法来获取数据并填充HTML中的select元素。
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;
})
});发布于 2013-10-21 22:54:16
我不会重新发明轮子,而是使用Django Smart Selects或Django Autocomplete Light
我也没有尝试过,但我即将在即将到来的项目中使用它们中的一个或两个。
https://stackoverflow.com/questions/14121132
复制相似问题