【问题标题】:Django send welcome email after User created using signals使用信号创建用户后,Django 发送欢迎电子邮件
【发布时间】:2017-07-31 14:06:04
【问题描述】:

我有一个 create_user_profile 信号,我想使用相同的信号向用户发送欢迎电子邮件。

这是我目前在 signals.py 中所写的内容:

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    instance.profile.save()

    subject = 'Welcome to MyApp!'
    from_email = 'no-reply@myapp.com'
    to = instance.email
    plaintext = get_template('email/welcome.txt')
    html = get_template('email/welcome.html')

    d = Context({'username': instance.username})

    text_content = plaintext.render(d)
    html_content = html.render(d)

    try:
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
    except BadHeaderError:
        return HttpResponse('Invalid header found.')

这是失败并出现此错误:

TypeError at /signup/
context must be a dict rather than Context.

指向我的views.py 文件中的forms.save。 你能帮我理解这里出了什么问题吗?

【问题讨论】:

    标签: email django-signals django-1.11


    【解决方案1】:

    只需将 dict 传递给渲染而不是 Context 对象

    d = {'username': instance.username}
    text_content = plaintext.render(d)
    

    【讨论】:

      【解决方案2】:

      在 django 1.11 上,模板上下文必须是一个字典: https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.base.Template.render

      尝试只删除上下文对象创建g。

      d = {'username': instance.username}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-13
        • 2021-10-26
        • 2015-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多