Search code examples
emaildjango-signalsdjango-1.11

Django send welcome email after User created using signals


I have a create_user_profile signal and I'd like to use same signal to send a welcome email to the user.

This is what I wrote so far in my 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.')

This is failing with this error:

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

pointing to the forms.save in my views.py file. Can you help me to understand what's wrong here?


Solution

  • On django 1.11 the template context must be a dict: https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.base.Template.render

    Try to just remove the Context object creationg.

    d = {'username': instance.username}