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

Django视图返回普通变量报AttributeError: 'int' object has no attribute 'get'

解决Django视图返回原始类型触发AttributeError的问题

问题原因

Django要求视图函数必须返回一个HttpResponse类(或其子类)的实例,直接返回int、字符串、列表这类原始数据类型时,Django会尝试调用返回值的get()方法(WSGI协议要求响应对象需具备该方法),但原始类型没有这个方法,因此触发AttributeError: 'int' object has no attribute 'get'。

解决方案

根据返回内容类型,选择对应的响应对象:

1. 返回纯文本/数值

用HttpResponse包裹数据,注意将数值转为字符串:

from django.http import HttpResponse

def my_view(request):
    # 返回int类型3
    return HttpResponse(str(3))
    # 返回字符串示例
    # return HttpResponse("Hello World")

2. 返回JSON格式数据

返回列表、字典等结构化数据时,推荐用JsonResponse自动处理序列化:

from django.http import JsonResponse

def my_view(request):
    # 返回数值3(自动转为JSON格式)
    return JsonResponse(3, safe=False)
    # 返回列表示例
    # return JsonResponse([1,2,3], safe=False)
    # 返回字典示例(safe默认True,无需修改)
    # return JsonResponse({"key": "value"})

注意:返回非字典的JSON数据时,需设置safe=False,否则会抛出TypeError。

3. 返回HTML模板

若需渲染页面,使用render函数(本质仍返回HttpResponse实例):

from django.shortcuts import render

def my_view(request):
    context = {"number": 3}
    return render(request, "my_template.html", context)

验证

修改代码后重启项目,访问对应路由,即可避免AttributeError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:05:23