Skip to content
Advertisement

Why django dependent dropdownn is not working

I cant tell where there is an error in my code. It just doesnt work as expected. My views.py

def load_cities(request):
    year_id = request.GET.get('year')
    terms = Term.objects.filter(school=request.user.school).filter(year_id=year_id).order_by('name')
    return render(request, 'city_dropdown_list_options', {'terms': terms})

My models.

class Year(models.Model):
    
    school = models.ForeignKey(School,on_delete=models.CASCADE)
    year = models.CharField(max_length=200,unique=True)

class Term(models.Model):
    school = models.ForeignKey(School,on_delete=models.CASCADE)
    year = models.ForeignKey(Year,on_delete=models.CASCADE)
    name = models.CharField(max_length=200,unique=True) 

class Exam(models.Model):
    school = models.ForeignKey(School,on_delete=models.CASCADE)
    year = models.ForeignKey(Year,on_delete=models.SET_NULL, null=True)
    term = models.ForeignKey(Term,on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=20)
    form = models.ManyToManyField(FormModel)

My forms.py

    class NewExamForm(forms.ModelForm):
        class Meta:
            model = Exam
            fields = ("year","term","name","school","form")
            
            widgets = {
                'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}),
                "year":forms.Select(attrs={"class":'form-control'}),
                "name":forms.TextInput(attrs={"class":'form-control'}),
                "form":forms.Select(attrs={"class":'form-control'}),
                
            }
        def __init__(self, school, *args, **kwargs):
            super(NewExamForm, self).__init__(*args, **kwargs)
            
            
            self.fields['year'] = forms.ModelChoiceField(
                queryset=Year.objects.filter(school=school))
    
            self.fields['term'].queryset = Term.objects.none()
    
            self.fields['form'] = forms.ModelMultipleChoiceField(
                queryset=FormModel.objects.filter(school=school),
                widget=forms.CheckboxSelectMultiple,
                required=True)
            
            if 'year' in self.data:
                try:
                    year = int(self.data.get('year'))
                    self.fields['term'].queryset = Term.objects.filter(school=school).filter(year_id=year).order_by('name')
                except (ValueError, TypeError):
                    pass  # invalid input from the client; ignore and fallback to empty City queryset
            elif self.instance.pk:
                self.fields['term'].queryset = self.instance.year.term_set.order_by('name')

The template

<div class="form-group">
        <form method="post" id="examForm" data-cities-url="{% url 'ajax_load_cities' %}" novalidate enctype="multipart/form-data">
        {% csrf_token %}
        <table>
          {{ form|crispy }}
        </table>
        <button type="submit">Save</button>
        </form>
        
    </div>

I have tried but it works only after I select a year and refresh manually with the year selcted, that’s when the terms appear.

I tried following the code by Vitor Freitas but couldn’t get it working. Anyone with the knowhow to assist.

Advertisement

Answer

I got it working by making corrections on the script as directed by @evergreen.

<script>

$("#id_year").change(function () {
  var url = $("#examForm").attr("term-data");
  var yearId = $(this).val();

  $.ajax({
    url: url,
    data: {
      'year': yearId
    },
    success: function (data) {
      $("#id_term").html(data);
    }
  });

});
  </script>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement