1

我有一个 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。你能帮我理解这里有什么问题吗?

4

2 回答 2

1

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

d = {'username': instance.username}
text_content = plaintext.render(d)
于 2017-07-31T14:32:48.440 回答
0

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

尝试仅删除 Context 对象创建。

d = {'username': instance.username}
于 2017-07-31T14:23:59.153 回答