在这里,在从模板中添加学生费用信息时,如果用户选择某些课程,则只有该所选课程的 basic_price 和 advance_price 应该显示在选择费用选项中。我怎样才能实现这一点?
学生费用.html
<div class="form-group">
<h5>Course <span class="text-danger">*</span></h5>
<div class="controls">
<select name="course" id="personForm" data-fees-url="{% url 'students: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>
</div>
</div>
<div class="form-group">
<h5>Total Fee <span class="text-danger">*</span></h5>
<div class="controls">
<select name="total_fee" id="select3" required class="form-control">
<option value="">Select Fee</option>
</select>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
您需要创建一个新函数,该函数将返回特定于课程的费用,但从 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})
Run Code Online (Sandbox Code Playgroud)
关联模板:
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>
Run Code Online (Sandbox Code Playgroud)
在 urls.py 中添加以下内容:
path('ajax/load-course-fees/', views.ajax_course_fees, name='ajax_load_course_fees'),
Run Code Online (Sandbox Code Playgroud)
在您的模板中,您需要默认删除费用,它们将从每个课程的 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4704 次 |
| 最近记录: |