Django模板Ajax调用失败:Field 'id'期望数字却获值'populate_sections'
问题分析
触发Ajax时出现ValueError at /edit_student/populate_sections,提示Field 'id' expected a number but got 'populate_sections',核心原因是:
- 当前页面路径为
/edit_student/<student_id>,Ajax请求使用相对路径'populate_sections',导致实际请求地址变成/edit_student/populate_sections。 - Django路由匹配遵循先定义先匹配的规则,
path('edit_student/<student_id>', ...)会优先捕获该请求,把populate_sections当作student_id参数传入视图,但该参数要求是数字类型,因此抛出类型错误。
解决方案
方案1:用Django模板标签生成正确请求URL
在模板中通过{% url %}标签生成populate_sections的绝对路径,确保请求精准指向目标路由:
$("#id_class_name").change(function(){ var class_name = $(this).val(); $.ajax({ url: "{% url 'populate_sections' %}", // 替换为模板标签生成的URL type: 'GET', data: {class_name:class_name}, dataType: 'json', success: (data) => { $("#id_section_name").empty(); for( var i in data.context){ $("#id_section_name").append("<option value='"+data.context[i].id+"'>"+data.context[i].name+"</option>"); } } }); });
注意:这段JS代码必须写在Django模板文件(如
edit_student.html)内,才能让模板引擎解析{% url %}标签;如果JS在外部独立文件中,需要在模板里把URL赋值给全局变量,再在外部JS中调用。
方案2:调整路由顺序(可选)
将populate_sections的路由放在edit_student路由之前,让Django优先匹配精确路径:
urlpatterns = [ # 先定义精确匹配的路由 path('populate_sections', views.populate_sections, name="populate_sections"), # 再定义带参数的路由 path('edit_student/<student_id>', views.edit_student, name="edit_student"), .......... ]
这种方式下,原Ajax的相对路径'populate_sections'会被正确解析为根路径下的/populate_sections,不会被误匹配为student_id。
方案3:给populate_sections添加子路径前缀(可选)
如果希望populate_sections属于edit_student的子路由,可调整路由并确保精确匹配优先:
urlpatterns = [ path('edit_student/populate_sections', views.populate_sections, name="populate_sections"), path('edit_student/<student_id>', views.edit_student, name="edit_student"), .......... ]
此时Ajax的相对路径'populate_sections'会被解析为/edit_student/populate_sections,由于精确匹配路由在前,不会触发带参数的路由规则。
内容的提问来源于stack exchange,提问作者BullHump
相关产品推荐
相关产品推荐

