如何在Django中不使用rest_framework返回JSON数据?
你调用JsonResponse报错的核心原因是参数规则误用:
render方法的参数为render(request, 模板路径, 上下文数据),用于渲染HTML页面返回给前端JsonResponse是专门用来返回JSON格式响应的类,第一个参数必须是可序列化为JSON的Python对象(通常是字典),你直接把request和模板路径作为参数传入,完全不符合参数要求,必然会抛出错误。
修正后的后端代码
# views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.core.mail import send_mail def contact_us(request): # 完全不需要渲染HTML的话,GET请求直接返回JSON提示 if request.method == "GET": return JsonResponse({"msg": "请使用POST方法提交联系信息", "code": 400}, status=400) if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") title = request.POST.get("title") message = request.POST.get("message") # 增加必填参数校验,避免发送无效空邮件 if not all([name, email, title, message]): return JsonResponse({"msg": "必填参数不能为空", "code": 400}, status=400) data = { "name": name, "email": email, "title": title, "message": message } # 注意不要和之前的message变量重名,避免覆盖 message_content = ''' New message: {} From: {} '''.format(data["message"], data['email']) send_mail(data["title"], message_content, '', ['mine@gmail.com']) # 直接传入要返回的JSON数据即可,返回字典不需要加safe=False return JsonResponse({"msg": "邮件发送成功", "code": 200, "data": data})
可选前端优化(表单提交不跳转拿JSON)
如果你的表单希望提交后不跳转,直接拿到后端返回的JSON数据,可在contact.html中加入如下原生JS代码,不需要额外引入依赖:
document.querySelector('.contact_us').addEventListener('submit', function(e) { e.preventDefault(); // 阻止表单默认跳转行为 const formData = new FormData(this); fetch(window.location.href, { method: 'POST', body: formData }).then(res => res.json()) .then(data => { console.log('返回的JSON数据:', data); // 可自行扩展成功/失败的前端提示逻辑 if(data.code === 200) alert('提交成功'); else alert(data.msg); }) })
内容的提问来源于stack exchange,提问作者C-Bizz
相关产品推荐
相关产品推荐

