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

如何在Django的send_mail()中调用多变量并解决相关报错

Django send_mail() 多变量传入及错误解决

问题分析

你遇到的两个错误原因明确:

  • 'list' object has no attribute 'splitlines':Django的send_mail()函数要求第二个参数message必须是字符串类型,你传入了列表,导致内部调用splitlines()方法时触发类型错误。
  • "send_mail got multiple values for argument fail_silently":通常是传参顺序错误或位置参数与关键字参数混用导致的,比如曾错误地将列表拆分为多个位置参数传入,覆盖了后续关键字参数的位置。

解决方案

将多个变量拼接成格式化的字符串作为message参数即可,推荐用Python的f-string实现清晰易读的格式:

修改views.py中的send_mail调用部分:

def maintenance(request):
    if request.method == 'POST':
        employeeid = request.POST.get('employee-id')
        name = request.POST.get('name')
        email = request.POST.get('email')
        fromplace = request.POST.get('from-place')
        toplace = request.POST.get('to-place')
        vehicle = request.POST.get('vehicle')
        duration = request.POST.get('duration')

        # 把变量拼接为格式化的邮件内容字符串
        message = f"""
员工提交信息:
Employee ID: {employeeid}
姓名: {name}
邮箱: {email}
出发地: {fromplace}
目的地: {toplace}
交通工具: {vehicle}
时长: {duration}
"""

        send_mail(
            'Employee Form',  # 邮件主题
            message,          # 邮件内容(字符串类型)
            settings.EMAIL_HOST_USER,  # 发件人
            ['a@gmail.com'],  # 收件人列表
            fail_silently=False
        )
    return render(request, "maintenance.html")

补充说明

你提到数据存储在Script标签中,实际上前端JavaScript仅负责表单自动填充,表单提交后数据仍会通过POST请求传递到后端views.py,当前的参数获取逻辑是正确的,无需修改前端代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:34:57