Django生成PDF支票报错:'dict' object has no attribute 'headers'
Django生成PDF支票时出现
'dict' object has no attribute 'headers'错误的排查解决 问题描述
编写了一个为客户生成PDF支票的Django方法,运行时抛出错误:'dict' object has no attribute 'headers',错误源自clickjacking.py。使用环境为Python 3.9 + CentOS 7,相关代码如下:
@csrf_exempt def generate_pdf(request): body = ujson.loads(request.body) monitoring = Monitoring.objects.filter(tr_id=body['tr_id']).first() if not monitoring: return { "message": MESSAGE['NotDataTrID'] } data = { 'headers': ["Abdulloh",], 'user': monitoring.user, 'tr_id': monitoring.tr_id, 't_id': monitoring.t_id, 'type': monitoring.type, 'pay_type': monitoring.pay_type, 'sender_token': monitoring.sender_token, } pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf')
错误原因
Django要求视图函数必须返回HttpResponse(或其子类)对象。当前代码中,当monitoring不存在时直接返回了一个字典,Django的clickjacking中间件会尝试对视图返回的对象调用.headers属性,而字典没有该属性,因此触发错误。
解决方案
- 导入
JsonResponse:在文件顶部添加导入语句
from django.http import JsonResponse
- 修改字典返回为
JsonResponse:将判断monitoring不存在时的返回逻辑替换为:
if not monitoring: return JsonResponse({"message": MESSAGE['NotDataTrID']}, status=404)
额外注意事项
- 若该接口无需CSRF验证,可保留
@csrf_exempt;若为前端调用,建议使用CSRF令牌机制提升安全性。 - 确保
render_to_pdf函数返回有效的PDF二进制内容,避免后续HttpResponse返回时出现异常。
内容的提问来源于stack exchange,提问作者Abdulloh Mahmudov
相关产品推荐
相关产品推荐

