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

Django用户注册遇AttributeError: tuple无splitlines属性求助

解决Django注册邮箱验证中tuple对象无splitlines属性的错误

这个错误的根源很明确:你在生成邮件正文时,意外将message变量赋值成了一个元组(tuple),而Django的email_user方法要求接收字符串类型的邮件内容。

问题代码定位

看你这段代码:

message = render_to_string('login/account_activation_email.html'), {
    'user':user,
    'domain':current_site.domain,
    'uid':urlsafe_base64_encode(force_bytes(user.pk)),
    'token':account_activation_token.make_token(user),
}

这里render_to_string(...)后面多了一个右括号,再加上逗号和后面的字典,被Python解释器打包成了一个元组(渲染后的字符串, 上下文字典),而不是你期望的、经过模板渲染后的HTML字符串。当Django尝试对这个元组调用splitlines()方法处理邮件格式时,自然就抛出了AttributeError。

修正方案

把多余的右括号去掉,将上下文字典作为render_to_string的第二个参数传入:

message = render_to_string('login/account_activation_email.html', {
    'user':user,
    'domain':current_site.domain,
    'uid':urlsafe_base64_encode(force_bytes(user.pk)),
    'token':account_activation_token.make_token(user),
})

额外的逻辑优化建议

另外注意,你在设置user.is_active = False(禁用账号直到激活)之后,还调用了login(self.request, user)——这在Django里是不生效的,因为默认情况下,is_active=False的用户无法通过认证登录。建议移除这段登录代码,保持注册后让用户去邮箱激活账号的逻辑:

def form_valid(self, form):
    user = form.save(commit=False)
    user.is_active = False # 账号激活前保持禁用状态
    user.save()

    current_site = get_current_site(self.request)
    subject = 'Activate Your Account'
    message = render_to_string('login/account_activation_email.html', {
        'user':user,
        'domain':current_site.domain,
        'uid':urlsafe_base64_encode(force_bytes(user.pk)),
        'token':account_activation_token.make_token(user),
    })
    
    user.email_user(subject, message)

    messages.add_message(
        self.request,
        messages.SUCCESS,
        'Check Your Email For Account Activation Link'
    ) 

    # 移除无效的登录代码
    # if user is not None:
    #     login(self.request, user)
    return super(UserRegister, self).form_valid(form)

这样修正后,邮件正文会被正确生成为字符串,email_user方法就能正常处理邮件,不会再抛出tuple相关的错误,同时注册逻辑也更符合邮箱验证的预期流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:30:59