You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中Ajax调用UpdateView出现URL未找到问题求助

解决Ajax调用Django UpdateView时的URL未找到错误

核心问题排查

你遇到的404错误主要来自三个关键点:

  • URL路由要求必须传入<int:pk>参数,但你的Ajax请求URL/register-non-device/view/没有携带pk值,导致Django无法匹配到对应路由
  • Ajax的data参数格式错误,直接传递$(this).val()会导致请求参数不符合后端预期
  • 默认的UpdateView的GET请求只会返回表单页面,无法直接返回JSON数据

修复步骤

1. 修正Ajax请求的URL与参数格式

将URL拼接上pk参数,同时规范data的传递格式:

$(document).on("change", "#id_device_type", function() {
    const pk = $(this).val();
    $.ajax({
        url: `/register-non-device/view/${pk}/`,  // 动态拼接pk参数
        type: "GET",
        dataType: 'json',
        data: {}  // 无额外参数可留空,按需添加键值对
    });
});

优化建议:避免硬编码URL,可在模板中用{% url 'register-non-device' pk=0 %}生成基础URL后替换pk值,外部JS文件可通过前端变量传递URL模板

2. 保持URL配置正确性(当前配置无需修改)

你的URL规则是正确的,只要请求URL携带合法pk即可匹配:

path('register-non-device/view/<int:pk>/', RegisterNonDeviceView.as_view(), name='register-non-device')

3. 重写UpdateView的get方法以返回JSON响应

默认UpdateView的GET请求会渲染模板,需要重写方法处理AJAX请求的JSON返回:

from django.http import JsonResponse
from django.views.generic.edit import UpdateView

class RegisterNonDeviceView(UpdateView):
    model = AnticipatedNonDevice
    form_class = AnticipatedNonDeviceForm
    template_name = 'anticipated_non_device.html'
    success_url = reverse_lazy('app:po-search-non-device')

    def get(self, request, *args, **kwargs):
        # 识别AJAX请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            self.object = self.get_object()
            # 构造需要返回的JSON数据
            response_data = {
                'id': self.object.id,
                'device_type': self.object.device_type,
                # 按需添加其他字段
            }
            return JsonResponse(response_data)
        # 非AJAX请求走默认逻辑
        return super().get(request, *args, **kwargs)

额外提醒

  • 若需通过AJAX执行更新操作,应使用POST请求,并在Ajax中携带CSRF令牌:添加headers: {'X-CSRFToken': document.cookie.split('csrftoken=')[1].split(';')[0]}
  • 确保#id_device_type的value是有效的模型主键值,否则即使URL正确,也会因找不到对象返回404

内容的提问来源于stack exchange,提问作者Abzal Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:32:26