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

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

问题描述

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

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.

例如,我有 3 个校区,比如 Campus1、Campus2、Campus3.如果我选择 Campus1,我应该只能选择 Campus1 中的学校并继续此操作,如果我选择 School1,那么我需要能够选择 School1 的中心,并且所有其他选项都应该隐藏.

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.

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

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.

请指导我这样做.

谢谢

推荐答案

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

You might need to use the following technologies:

  • 自定义 Django 表单字段(在模型表单中)
  • ajax(获取记录)
  • simplejson(向ajax发送json响应)
  • jquery(更新客户端的组合框)

让我们看一个例子(没有真正测试过这个,只是我的想法):

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

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

现在,在您的视图中编写一个方法,为校园下的学校和学校下的中心返回一个 json 对象:

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

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 元素.

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

$(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天全站免登陆