使用jQuery在django中实现相互依赖的下拉菜单的最简单方法

时间:2014-06-17 10:42:48

标签: jquery python django

任何人都可以给出如何使用jQuery在django中实现相互依赖的下拉菜单的基本示例吗? 我试过了,但我只得到一个下拉菜单。

Models.py

def get_photo_storage_path(photo_obj, filename):     
    random_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10))
    storage_path = 'img/profile/' + random_string + '_' + filename
    return storage_path  

class CompanyMake(models.Model):
    company_name = models.CharField(max_length = 100)
    def __unicode__(self):
        return self.company_name

class MakeModel(models.Model):
    company = models.ForeignKey(CompanyMake)
    model_name = models.CharField(max_length = 100)
    def __unicode__(self):
        return self.model_name

class ModelParts(models.Model):
    company = models.ForeignKey(CompanyMake)
    model = models.ForeignKey(MakeModel)
    part_name = models.CharField(max_length = 100)
    def __unicode__(self):
        return self.part_name

class ModelYear(models.Model):
    company = models.ForeignKey(CompanyMake)
    model = models.ForeignKey(MakeModel)
    year_value = models.IntegerField()


class UserProfile(models.Model):
    user = models.OneToOneField(User,primary_key=True)   
    #image = models.ImageField(upload_to=get_photo_storage_path, null = True, blank=True)
    part = models.ForeignKey(ModelParts,null = True, blank=True) 
    phone_number = models.CharField( max_length = 10,verbose_name="Mobile Number 10 digits",null = True, blank=True, default=None)

views.py是

def home(request):
    cm = CompanyMake.objects.all()
    for a in cm:
        print a
        mm = a.makemodel_set.all()
        for b in mm:
            print b
            mp = b.modelparts_set.all()
            for c in mp:
                print c
                my = ModelYear.objects.all()
                print my

        return render(request,'choice.html',{'cm':cm,'mm':mm, 'mp':mp, 'my':my})

forms.py是

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        exclude=('user')

choice.html是

<select name="car">
    {% for car in cm %}

            <option value="{{car.key}}" selected="selected">{{car.company_name}}</option>

    {% endfor %}
</select>

        <br/>

            <select name="car">
    {% for model in mm %}
            <option value="{{model.key}}" selected="selected">{{model.model_name}}</option>
            {% endfor %}
</select>

在这里,我试图获得汽车模型和零件的相互依赖的下拉列表。

1 个答案:

答案 0 :(得分:1)

最简单的方法是通过第一个下拉菜单的更改事件的ajax调用。

将您的choice.html更改为:

<select id = "selectbox1">
  <option>Please Select Car Company</option>
  {% for car in cm %}
    <option value = "{{car.id}}"> {{car.company_name}} </option>
  {% endfor %}
</select>

<select id = "selectbox2">
  <option>Select Car Company First</option>
</select>

现在更改selectbox1的选项时,您必须获取selectbox2选项的值(使用ajax)并将其放入selectbox2

的html中

在Javascript中(假设您使用Jquery),您可以:

$('#selectbox1').on("change", function(){
  $.get("fetch_options2/"+$('#selectbox1').val(),
    function (data){
      $('#selectbox2').html(data);
    }
, "html")
});

现在对于服务器端:

在urls.py中:

url(r'fetch_options2/([0-9]+)$', 'fetch_options2', name='fetch_options2'),

在views.py中:

def fetch_options2(request, car_company_id):
   opt2_html = ""
   try:
     company = CompanyMake.objects.get(pk = car_company_id)
     make_models  = company.makemodel_set.all()
     for model in make_models:
       opt2_html += "<option value='"+str(model.id)+"'>"+model.model_name+"</option>"
   except:
     write_exception("Error in fetching options 2")
   return HttpResponse(opt2_html)

那就是它。如果您遇到任何问题,请告诉我。