求助:Django中POST请求触发TypeError,'method'对象不可下标
解决联系表单数据库对接的TypeError错误
核心错误原因
request.POST.get 是一个方法,必须使用**括号()**调用,你错误地使用了方括号[],导致触发 'method' object is not subscriptable 错误。此外代码还存在缩进错误和对象赋值错误,以下是完整修正方案:
修正后的views.py代码
# Create your views here. def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def project(request): return render(request, 'project.html') def contact(request): if request.method == 'POST': # 修正get方法的调用方式:用()替代[] name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') concern = request.POST.get('concern') # 可选:添加基础表单验证,避免空数据存入数据库 if name and email and phone and concern: # 修正对象赋值:用变量而非固定字符串 obj = Contact(name=name, email=email, phone=phone, concern=concern) obj.save() # 确保GET请求或POST请求完成后都能返回页面 return render(request, 'contact.html')
关键修正点说明
- 方法调用错误:
request.POST.get('key')是正确用法,方括号[]用于直接访问字典元素(如request.POST['name']),但get方法需要括号传参 - 缩进错误:原代码中email、phone等变量定义在if块外,GET请求时会因name未定义报错,需缩进至if块内
- 对象赋值错误:原代码中
name='name'会把固定字符串存入数据库,应改为name=name使用用户提交的变量值 - 基础验证:添加字段非空检查,避免无效空数据写入数据库
内容的提问来源于stack exchange,提问作者Saba khalid
相关产品推荐
相关产品推荐

