You need to enable JavaScript to run this app. Django使用smart_str导出CSV时报NoneType属性错误的解决方法问询
优惠活动
大模型
产品
解决方案
定价
更多

Django使用smart_str导出CSV时报NoneType属性错误的解决方法问询

问题根因

你遇到的报错来自两个逻辑错误,和smart_str本身的容错能力无关:

  • smart_str参数调用错误:smart_str的入参规则为第一个参数是待转换的目标值,后续参数为编码规则、错误处理策略等配置项。你同时传入三个姓名字段给smart_str,会导致方法内部逻辑执行异常。如果要拼接监护人全名,需要先把三个字段拼接为完整字符串,再传入smart_str转换。
  • 关联外键为空未做判空处理:链式调用report.Student_Users.Parent_Users.xxx时,如果Student_Users或Parent_Users关联记录不存在(字段值为None),直接访问后续属性就会触发NoneType无对应属性的报错。
修复方案

调整后的完整代码如下,同时增加了空值容错、smart_str错误自动忽略的配置:

import csv
from django.utils.encoding import smart_str
from django.http import HttpResponse

def downloadcv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="StudentEnrollmentRecord.csv"'

    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8'))
    # 表头部分无需特殊调整,本身就是固定字符串
    writer.writerow([
       smart_str(u"Guardians_Fullname", errors='replace'),
       smart_str(u"Guardians_Address", errors='replace'),
       smart_str(u"Contact_Number", errors='replace'),
    ])
    reports = StudentsEnrollmentRecord.objects.filter(School_Year=yearid).order_by('Education_Levels','-Date_Time')
    for report in reports:
        # 先判空关联外键,避免None访问属性报错
        parent_user = None
        if report.Student_Users and hasattr(report.Student_Users, 'Parent_Users'):
            parent_user = report.Student_Users.Parent_Users
        # 所有字段先处理空值
        last_name = getattr(parent_user, 'Guardian_LastName', "") or ""
        first_name = getattr(parent_user, 'Guardian_FirstName', "") or ""
        initial = getattr(parent_user, 'Guardian_Middle_Initial', "") or ""
        address = getattr(parent_user, 'Guardian_Address', "") or ""
        contact = getattr(parent_user, 'Contact_Number', "") or ""
        # 先拼接全名,再传给smart_str,加errors='replace'遇到不可转换字符自动替换不报错
        full_name = f"{last_name}{first_name} {initial}".strip()
        writer.writerow([
            smart_str(full_name, errors='replace'),
            smart_str(address, errors='replace'),
            smart_str(contact, errors='replace'),
        ])
    return response
核心调整点说明
  • 给smart_str增加errors='replace'参数:所有无法被正常编码的字符会自动被替换为?,不会抛出编码错误。
  • 关联外键增加判空逻辑:用hasattr、getattr避免空关联对象访问属性报错,所有空值默认替换为空字符串。
  • 修正smart_str调用逻辑:先拼接好完整的字段内容,再传入smart_str做编码转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 20:24:02