[Django]-How to display dependent drop-down in django form

5👍

You need to create a new function that will return the fees specific to a course, but called from ajax

def ajax_course_fees(request):
    course = Course.objects.get(pk=request.GET.get('course_pk'))
    #generate an html template for the specific option
    return render(request, 'fees_dropdown_list_options.html', {'course': course})

the associate template:

fees_dropdown_list_options.html

<option value="">Select Fee</option>
<option value="{{course.basic_price}}">{{course.basic_price}}(Basic)</option>
<option value="{{course.advanced_price}}">{{course.advanced_price}}(Advanced)</option>
       

In urls.py add this:

 path('ajax/load-course-fees/', views.ajax_course_fees, name='ajax_load_course_fees'),

In your template you need to remove the fees by default, they will be dynamically loaded from ajax call for each Course

And I provide the Jquery to make the ajax call.

<select name="course" id="select2" data-fees-url="{% url 'ajax_load_course_fees' %}" required class="form-control">
    <option value="">Select Course</option>
        {% for course in courses %}
            <option value="{{course.id}}">{{course.title}}</option>
        {% endfor %}
</select>
<select name="total_fee" id="select3" required class="form-control">
    <option value="">Select Fee</option>
</select>


 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $("#select2").change(function () {
      var url = $("#select2").attr("data-fees-url");  // get the url of the ajax_load_course_fees view
      var course_pk = $(this).val();  // get the selected course pk from the HTML input

      $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request
        data: {
          'course_pk': course_pk       // add the course pk to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `ajax_course_fees` view function
          $("#select3").html(data);  // replace the contents of the fees select with the data that came from the server
        }
      });

    });
  </script>

And for you information: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

Leave a comment