Django依赖选择

时间:2014-09-07 02:48:46

标签: jquery python django

我知道这个问题有很多答案,但我是Django的新手,我不知道如何实现这些解决方案。首先我想做什么。这是我的模特:

class Region(models.Model):

    name = models.CharField(max_length=255, verbose_name=_("Name"))
    slug = models.SlugField(max_length=150, unique=True, null=True)

    def save(self,*args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Region,self).save(*args,**kwargs)

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

    class Meta:
        verbose_name = _('Region')
        verbose_name_plural = _('Regions')

class District(models.Model):

    name = models.CharField(max_length=255, verbose_name=_("Name"))
    slug = models.SlugField(max_length=150, unique=True, null=True)
    region = models.ForeignKey(Region,verbose_name=_("Region"))

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(District, self).save(*args, **kwargs)

    def is_in_region(self, region):
        if self.region == region:
            return True
        else:
            return False

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

    class Meta:
        verbose_name = _("District")
        verbose_name_plural = _("Districts")

在前端页面中,我想选择一个区域,选择区域将显示该区域的区域。我的意见如下:

class SearchView(ListView):

    template_name = 'advert/list_view.html'

    def all_json_models(self, request, region):
        current_reg = Region.objects.get(slug=region)
        districts = District.objects.all().filter(region=current_reg)
        json_models = serializers.serialize("json", districts)
        return http.HttpResponse(json_models, mimetype="application/javascript")

    def get(self, request, *args, **kwargs): 
        return self.post(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.request = request
        try:
            self.page = int(self.request.GET.get('page','1'))
        except:
            self.page = 1
        self.queryset = ""
        return super(SearchView, self).get(request, *args, **kwargs)

    def get_queryset(self):
        """We have to bypass the queryset because
        we are joining several object lists together. """
        return None

    def get_context_data(self, **kwargs):
        context['regions'] = Region.objects.all().order_by("name")
        return context

get_context_data方法要长得多,但我在这里只写了一个简单的方法。我在本网站使用此解决方案http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/。但仍然选择与地区不起作用。我尝试在视图中将方法all_json_models写入此类,但仍然不调用此方法。在这里有谁能告诉我为什么?很多

4 个答案:

答案 0 :(得分:15)

好吧,我为你编写了一个完整的项目,希望这可以帮助:):
在这个项目中,我们有许多城市的国家 如图所示,每次选择一个国家时,只有下一个组合框中显示的相关城市:)

iran's cities

USA's cities

好吧,不要让我们看看代码
(完整项目源代码在我的github上:https://github.com/nodet07/Django-Related-DropDowns
   models.py:
   只有2个简单的模型,一个可以拥有多个城市的国家!

 from django.db import models
    class City(models.Model):
        name = models.CharField(max_length=50)
        country = models.ForeignKey("Country")
        def __unicode__(self):
            return u'%s' % (self.name)

    class Country(models.Model):
        name = models.CharField(max_length=50)
        def __unicode__(self):
            return u'%s' % (self.name)

views.py:

from django.shortcuts import render
from map.models import *
from django.utils import simplejson
from django.http import HttpResponse

def index(request):
    countries = Country.objects.all()
    print countries
    return render(request, 'index.html', {'countries': countries})

def getdetails(request):
    #country_name = request.POST['country_name']
    country_name = request.GET['cnt']
    print "ajax country_name ", country_name

    result_set = []
    all_cities = []
    answer = str(country_name[1:-1])
    selected_country = Country.objects.get(name=answer)
    print "selected country name ", selected_country
    all_cities = selected_country.city_set.all()
    for city in all_cities:
        print "city name", city.name
        result_set.append({'name': city.name})
    return HttpResponse(simplejson.dumps(result_set), mimetype='application/json',     content_type='application/json')

index.html:

<html>
    <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
        <script>
            $(document).ready(function(){
                 $('select#selectcountries').change(function () {
                     var optionSelected = $(this).find("option:selected");
                     var valueSelected  = optionSelected.val();
                     var country_name   = optionSelected.text();


                     data = {'cnt' : country_name };
                     ajax('/getdetails',data,function(result){

                            console.log(result);
                            $("#selectcities option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectcities").append('<option>'+ result[i].name +'</option>');
                            };


                         });
                 });
            });
        </script>
    </head>

    <body>
        <select name="selectcountries" id="selectcountries">
        {% for item in countries %}
            <option val="{{ item.name }}"> {{ item.name }} </option>    
        {% endfor %}
        </select>   


        <select name ="selectcities" id="selectcities">


        </select>

    </body>
</html>

答案 1 :(得分:1)

我厌倦了这种非DRY解决方案,所以我写了一些可能足够灵活的东西用于大多数用例:

django-related-select

现在它只处理在线/ AJAX相关的选择框。我最终计划(可能在本周或下一周)添加一个离线模式,该模式使用小部件推送一些渲染的JS来跟踪父级的onchange事件,并通过值映射将其转换为子选项 - &gt;列表(选择)。 AJAX解决方案非常适合汽车制造/模型(1000种选择),而离线解决方案非常适合产品/颜色(可能有10种选择)。

答案 2 :(得分:0)

您可以使用链接的Jquery插件。

实施例: http://codepen.io/anon/pen/EapNPo?editors=101

<强> HTML

<select id="id_country" name="country">
    <option value="" selected="selected">---------</option>
    <option value="1">Colombia</option>
    <option value="2">Rusia</option>
</select>
<select id="id_city" name="city">
    <option value="" selected="selected">---------</option>
    <option value="1" class="1">Bogotá</option>
    <option value="2" class="2">Moscú</option>
    <option value="3" class="2">San Petersburgo</option>
    <option value="4" class="1">Valledupar</option>
</select>

<强> JS

$("#id_city").chained("#id_country");

使用模型生成表单(ForeignKey)

转到https://axiacore.com/blog/django-y-selects-encadenados/完整教程

答案 3 :(得分:0)

此处提供了有关AJAX代码的更新答案,以及为清晰起见添加了一些补充内容。在下面,只需将#selectyear更改为您的选择ID,然后将变量schedule_year重命名为对您的数据有意义的名称。然后将#selectschedule成功更改为第二个选择ID的名称。请注意,result[i].schedule_name对应于从视图传回的值的名称。请查看views.py result_set,并相应地更改数据名称。

如果您要实现两个以上的链式选择,这很简单。只需复制下面的代码即可将每个序列链接在一​​起,以获得所需的尽可能多的关系。重复使用带有条件语句的同一视图,或仅添加另一个返回新结果的视图。

javascript和AJAX

<script>
$(document).ready(function(){
    //handle selected year
    $('select#selectyear').change(function () {
        var optionSelected = $(this).find("option:selected");
        var valueSelected  = optionSelected.val();
        var schedule_year   = optionSelected.text();
        $.ajax({
            url: 'getdetails/',
            type: 'GET',
            data: {'year' : JSON.stringify(schedule_year)},
            success:    function(result){
                            //remove previous selections
                            $("#selectschedule option").remove();
                            //add a blank option
                            $("#selectschedule").append('<option></option>');
                            //append new options returned
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectschedule").append('<option>'+ result[i].schedule_name +'</option>');
                            };
                        },
        });
    });
});
</script>

HTML

<table width="100%" class="table">
   <tr>
      <td class="align-middle" style="width: 50%;">
         <label for="#selectyear" value="calendar_year" style="width:100%">
            <span class="small pl-1">Select Calendar Year</span>
            <select class="form-control" name="selectyear" id="selectyear">
               <option value="blank"></option>
                  {% for schedule in schedules|dictsort:'fee_schedule_calendar_year' %}
                     {% ifchanged %}<!--used to only show unique values-->
                     <option value="{{ schedule.fee_schedule_calendar_year }}">{{ schedule.fee_schedule_calendar_year }}</option>
                     {% endifchanged %}     
                  {% endfor %}
            </select>
         </label>
      </td>
      <td class="align-middle" style="width: 50%;">
         <label for="#selectschedule" value="fee_schedule" style="width: 100%;">
         <span class="small pl-1">Select Fee Schedule</span>
            <select class="form-control" name="selectschedule" id="selectschedule"></select>
         </label>
      </td>
   </tr>
</table>

Views.py

# Handle AJAX request for fee schedule calendar year select
def getdetails(request, file_upload_id, file_header_id):
    schedule_year = json.loads(request.GET.get('year'))
    result_set = []
    schedules = FeeSchedule.objects.filter(fee_schedule_calendar_year=schedule_year)
    for schedule in schedules:
        result_set.append({'schedule_name': schedule.fee_schedule_name})
    return HttpResponse(json.dumps(result_set, indent=4, sort_keys=True, default=str), content_type='application/json')

urls.py

path('whatever_your_current_path_is_for_this_view/getdetails/', login_required(views.getdetails), name='get_details'),