您需要创建一个新函数,该函数将返回特定于课程的费用,但从 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})
关联模板:
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>
在 urls.py 中添加以下内容:
path('ajax/load-course-fees/', views.ajax_course_fees, name='ajax_load_course_fees'),
在您的模板中,您需要默认删除费用,它们将从每个课程的 ajax 调用中动态加载
我提供了 Jquery 来进行 ajax 调用。
<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>
并为您提供信息:https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html