如何使用Modelform和jquery在django中获得相互依赖的下拉列表?

时间:2022-11-19 22:11:31

I am new to django and jquery. I am working on a django-based app where I have 3 drop downs in a form. 1. Campus 2. School 3. Centre

我是django和jquery的新手。我正在开发一个基于django的应用程序,我在表单中有3个下拉菜单。 1.校园2.学校3.中心

The hierarchy is Campuses have schools and schools have centres. I want to interlink these drop-downs.

等级是校园有学校和学校有中心。我想将这些下拉列表链接起来。

For example, I have got 3 campuses, say Campus1, Campus2, Campus3. If I select Campus1, I should only get to select schools in campus1 and continuing this, if I select School1 then I need to be able to select centres of School1 and all other options should get hidden.

例如,我有3个校区,比如Campus1,Campus2,Campus3。如果我选择Campus1,我应该只选择校园1中的学校并继续学习,如果我选择了School1,那么我需要能够选择School1的中心,所有其他选项都应该隐藏起来。

I searched on net and have tried this http://blog.devinterface.com/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/ but it doesn't seem to work for me. I have also checked this http://www.javascriptkit.com/script/script2/triplecombo.shtml but since I am using ModelForm to create forms, this doesn't fit to my needs.

我在网上搜索并试过这个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来创建表单,这不符合我的需要。

Please guide me to do this.

请指导我这样做。

Thanks

谢谢

2 个解决方案

#1


20  

You might need to use the following technologies:

您可能需要使用以下技术:

  • Custom Django Form Fields (Within the model form)
  • 自定义Django表单字段(在模型表单中)
  • ajax(to fetch the records)
  • ajax(获取记录)
  • simplejson(to send a json response to ajax)
  • simplejson(向ajax发送json响应)
  • jquery(to update the combo boxes on client side)
  • jquery(更新客户端的组合框)

Let's have a look at an example(Not really tested this, just from the top of my mind):

让我们来看一个例子(没有真正测试过这个,只是从我的脑海中开始):

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.name

Forms.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')

Now, write a method in your views that returns a json object for schools under a campus and centres under a school:

现在,在您的视图中编写一个方法,为校园下的学校和学校中心返回一个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")

Now write a ajax/jquery method to fetch the data and populate the select elements in the HTML.

现在编写一个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;
    })
});

#2


4  

Rather than re-inventing the wheel, I would use Django Smart Selects or Django Autocomplete Light

我会使用Django Smart Selects或Django Autocomplete Light,而不是重新发明*

I haven't tried either yet but I'm about to use one or both of them in an upcoming project.

我还没有尝试过,但我即将在即将开展的项目中使用其中一个或两个。

#1


20  

You might need to use the following technologies:

您可能需要使用以下技术:

  • Custom Django Form Fields (Within the model form)
  • 自定义Django表单字段(在模型表单中)
  • ajax(to fetch the records)
  • ajax(获取记录)
  • simplejson(to send a json response to ajax)
  • simplejson(向ajax发送json响应)
  • jquery(to update the combo boxes on client side)
  • jquery(更新客户端的组合框)

Let's have a look at an example(Not really tested this, just from the top of my mind):

让我们来看一个例子(没有真正测试过这个,只是从我的脑海中开始):

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.name

Forms.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')

Now, write a method in your views that returns a json object for schools under a campus and centres under a school:

现在,在您的视图中编写一个方法,为校园下的学校和学校中心返回一个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")

Now write a ajax/jquery method to fetch the data and populate the select elements in the HTML.

现在编写一个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;
    })
});

#2


4  

Rather than re-inventing the wheel, I would use Django Smart Selects or Django Autocomplete Light

我会使用Django Smart Selects或Django Autocomplete Light,而不是重新发明*

I haven't tried either yet but I'm about to use one or both of them in an upcoming project.

我还没有尝试过,但我即将在即将开展的项目中使用其中一个或两个。