0

Can any one give the basic example of how to implement the interdependent drop-down menu in django using jQuery? I tried that but I am getting only one drop-down menu.

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 is

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 is

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

choice.html is

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

Here I am trying to get interdependent drop-down for car model and parts.

2
  • By interdependence you mean the second select box's options depend on the first select box's selected value? Commented Jun 17, 2014 at 13:13
  • Yes you are right. Car company has car models, car models has specific parts. so when i select any car then in next dropdown menu the only the car models which are related to that car should be available. Same for parts. Commented Jun 18, 2014 at 3:19

1 Answer 1

2

Simplest way to do is via an ajax call on change event of the first drop-down menu.

Change your choice.html to :

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

Now on change of the options of selectbox1 you have to get the values(using ajax) of options of selectbox2 and put them in html of selectbox2

In Javascript(assuming you use Jquery) you do:

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

Now For server side:

In urls.py:

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

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

That's it. Let me know if you face any issues.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.