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

提交表单时触发AttributeError:'str'对象无'get'属性

问题原因

报错AttributeError: 'str' object has no attribute 'get'的根源是表单实例的cleaned_data属性被错误设置为字符串类型,而非预期的字典类型。当Django在表单验证后期调用_get_validation_exclusions()方法时,尝试对cleaned_data调用字典的get()方法,自然触发错误。

最可能的触发场景是你在SlugCleanMixin的clean_slug方法中,错误地将整个self.cleaned_data字典替换成了字符串值,比如类似这样的错误代码:

def clean_slug(self):
    new_slug = self.cleaned_data['slug'].lower()
    if new_slug == 'create':
        raise ValidationError('Slug may not be "create".')
    self.cleaned_data = new_slug  # 错误覆盖了整个cleaned_data字典
    return new_slug
解决方案

修正SlugCleanMixin的clean_slug方法,不要修改整个self.cleaned_data,只需返回清洗后的slug字符串即可。Django会自动将返回值存入cleaned_data对应的字段中:

class SlugCleanMixin:
    def clean_slug(self):
        new_slug = self.cleaned_data['slug'].lower()
        if new_slug == 'create':
            raise ValidationError('Slug may not be "create".')
        return new_slug

另外,检查是否存在其他自定义的全局clean方法,确保这类方法返回完整的cleaned_data字典,而非单个字符串值。例如全局clean方法需遵循以下结构:

def clean(self):
    cleaned_data = super().clean()
    # 在这里执行全局清洗逻辑
    return cleaned_data  # 必须返回完整的cleaned_data字典
验证修正

修改代码后重新提交表单:

  • 表单会正确生成cleaned_data字典
  • clean_slug方法返回的清洗后的值会被存入cleaned_data['slug']
  • 后续验证流程能正常调用cleaned_data.get()方法,不再抛出错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:10:01