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

Django表单数据存入数据库报错:'str' object has no attribute '_meta'

解决Django表单数据存入模型报错'str' object has no attribute '_meta'的问题

问题原因

报错的核心是创建Profile模型实例时,错误地将字段值写成了字符串字面量(比如name="name"),而非从POST请求中获取的变量。这种写法会让Django误把字符串当成模型相关对象处理,触发'str' object has no attribute '_meta'错误,同时也导致表单数据根本没有被存入数据库。

修正后的视图代码

from django.shortcuts import render
from .models import Profile

def index(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        address = request.POST.get('address')
        pin = request.POST.get('pin')
        contact = request.POST.get('contact')
        email = request.POST.get('email','')
        # 移除字段值的引号,使用表单提交的变量
        profile = Profile(name=name, address=address, pin=pin, contact=contact, email=email)  
        profile.save()
    return render(request , 'index.html')

额外建议

  • 检查前端表单的input标签name属性,确保和request.POST.get()中的参数完全匹配,否则无法正确获取表单数据
  • 建议添加必填字段验证逻辑,避免空值存入数据库,比如:
    if not name or not address:
        # 处理字段为空的情况,比如返回错误提示
        return render(request, 'index.html', {'error': '姓名和地址为必填项'})
    
  • 更规范的做法是使用Django的ModelForm,它能自动处理表单验证、模型实例创建,减少手动代码的出错概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:15:05