Django отправляет приветственное письмо после того, как пользователь создан с использованием сигналов

У меня есть сигнал 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 = '[email protected]'
    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.

указывая на form.save в моем файле views.py. Можете ли вы помочь мне понять, что здесь не так?


person davideghz    schedule 31.07.2017    source источник


Ответы (2)


В django 1.11 контекст шаблона должен быть dict: https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.base.Template.render

Попробуйте просто удалить создание объекта Contextg.

d = {'username': instance.username}
person Julio    schedule 31.07.2017

Просто передайте диктовку рендеру вместо объекта Context

d = {'username': instance.username}
text_content = plaintext.render(d)
person Dos    schedule 31.07.2017