如何使用Modelform和jquery获取django中的相互依赖的下拉列表? [英] How to get Interdependent dropdowns in django using Modelform and jquery?

查看:91
本文介绍了如何使用Modelform和jquery获取django中的相互依赖的下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢django和jquery。我正在使用一个基于django的应用程序,我在一个表单中有3个下拉列表。
1.校园
2.学校
3.中心



层次结构是校园有学校和学校有中心。我想互相链接这些下拉列表。



例如,我有3个校园,说Campus1,Campus2,Campus3。如果我选择Campus1,我只能选择校园里的学校1,如果我选择School1,我需要选择School1的中心,所有其他选项都应该被隐藏。



我在网上搜索,并尝试过 http://blog.devinterface.com/2011/ 02 / how-to-implementation-two-drop-down-on-each-other-using-django-and-jquery /
但是对我来说似乎不起作用。
我也检查过这个 http://www.javascriptkit.com/script/script2/triplecombo.shtml
,但由于我使用ModelForm创建表单,这不符合我的需要。



请指导我这样做。



谢谢

解决方案

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




  • 自定义Django表单字段(模型格式)

  • ajax(以获取记录)

  • simplejson(发送json响应到ajax)

  • jquery(更新客户端的组合框)



我们来看一个例子(没有真正测试过,只是从我头上):



Models.py



 从django.db导入模型

class Campus(models.Model )
name = models.CharField(max_length = 100,choices = choices.CAMPUSES)

def __unicode __(self):
return u'%s'%self.name

class学校(models.Model):
name = models.CharField(max_length = 100)
campus = models.ForeignKey(Campus)

def __unicode __(self):
return u'%s'%self.name

class Cen tre(models.Model):
name = models.CharField(max_length = 100)
school = models.ForeignKey(School)

def __unicode __(self):
返回u'%s'%self.name



Forms.py



 导入模型
from django import forms

class CenterForm(forms.ModelForm):
campus = forms .ModelChoiceField(queryset = models.Campus.objects.all())
school = forms.ModelChoiceField(queryset = models.School.objects.none())#需要使用jquery填充这个
center = forms.ModelChoiceField(queryset = models.Centre.objects.none())#需要使用jquery填充这个

class Meta:
model = models.Center

fields =('campus','school','center')

现在,写一个方法在你的意见中,返回一个校园里的学校的json对象,并在一所学校的下方:



Views.py



  import model 
import simplejson
from django.http import HttpResponse

def get_schools(request,campus_id):
campus = models.Campus。 object.get(pk = campus_id)
schools = models.School.objects.filter(campus = campus)
school_dict = {}
在学校的学校:
school_dict [学校.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)
centers = models.Centre.objects.filter(school = school)
centre_dict = {}
为中心的中心:
centre_dict [centre.id] = centre.name
return HttpResponse(simplejson.dumps(centre_dict),mimetype =application / json)

现在编写一个ajax / jquery方法来获取数据并填充HTML中的选择元素。



AJAX / jQuery


$($($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
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)
);
});
}
});
返回false;
})
});


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

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.

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.

Please guide me to do this.

Thanks

解决方案

You might need to use the following technologies:

  • Custom Django Form Fields (Within the model form)
  • ajax(to fetch the records)
  • simplejson(to send a json response to ajax)
  • jquery(to update the combo boxes on client side)

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:

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

$(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;
    })
});

这篇关于如何使用Modelform和jquery获取django中的相互依赖的下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆