如何在Django DRF响应中返回字符串且避免AttributeError?
问题原因与修复方案
你遇到的问题很明确:你把format()方法调用在了字典对象上,但Python的字典(dict)并没有format这个方法——format()是字符串(str)类型专属的方法,所以才会抛出AttributeError: 'dict' object has no attribute 'format'。
你的代码里,{"Error": "build {} does not exist"}是一个字典,你试图直接对它调用.format(build_name),这完全找错了对象。正确的做法是把格式化操作应用在字典里的那个错误提示字符串上。
修复后的几种写法
写法1:使用字符串的format()方法(兼容Python 3.0+)
把format()移到字符串后面,先完成字符串的格式化,再把结果放进字典:
return Response({"Error": "build {} does not exist".format(build_name)}, status=status.HTTP_404_NOT_FOUND)
写法2:使用f-string(推荐,Python 3.6+)
这是Python 3.6及以后版本最简洁直观的字符串格式化方式:
return Response({"Error": f"build {build_name} does not exist"}, status=status.HTTP_404_NOT_FOUND)
写法3:旧式字符串格式化(兼容所有Python版本)
如果你需要兼容更老的Python版本,也可以用%操作符:
return Response({"Error": "build %s does not exist" % build_name}, status=status.HTTP_404_NOT_FOUND)
核心逻辑就是:格式化操作的目标必须是字符串,而不是包含字符串的字典,调整一下调用位置就解决问题啦。
内容的提问来源于stack exchange,提问作者Benihana
相关产品推荐
相关产品推荐

