16

私はdjangoとjqueryが初めてです。フォームに 3 つのドロップダウンがある django ベースのアプリに取り組んでいます。1. キャンパス 2. 学校 3. センター

階層は、キャンパスには学校があり、学校にはセンターがあります。これらのドロップダウンを相互にリンクしたい。

たとえば、Campus1、Campus2、Campus3 の 3 つのキャンパスがあります。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 を使用してフォームを作成しているため、これは私のニーズには合いません。

これを行うように私を導いてください。

ありがとう

4

2 に答える 2

29

次のテクノロジを使用する必要がある場合があります。

  • カスタム Django フォーム フィールド (モデル フォーム内)
  • ajax (レコードを取得するため)
  • simplejson (json レスポンスを ajax に送信するため)
  • 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

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 オブジェクトを返すメソッドをビューに記述します。

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

selectここで、データを取得して HTML に要素を設定する ajax/jquery メソッドを記述します。

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-01-02T12:28:06.843 に答える