django-registrationdjango-signalsuser-object

Add Django Variables in Email Template


I have a relatively simple objective: send email to Django admins when users register and activate their accounts that contain user information, like username, email, etc. I am using django-registration for handling the registration process. I then employ signals to send the emails. This process works just fine, but as soon as I try to inject the user, username or user's email into an email template I get in trouble.

Here is my signal_connectors.py:

from django.core.mail import mail_admins
from django.dispatch import receiver
from registration.signals import user_registered
from django.template.loader import render_to_string

@receiver(user_registered, dispatch_uid="common.signal_connectors.user_registered_handler")
def user_registered_handler(sender, **kwargs):

    print('user registration completed...')

    subject = 'registration notify'
    template = 'common/email.html'
    message = render_to_string(template, {'user': user})
    from_email = 'from@example.com'

    # send email to admins, if user has been registered
    mail_admins(subject, message, fail_silently=False, connection=None, html_message=None)

    print('sending email to administrators...')

The template is like so:

{{ user }} has registered at example.com

I have tried variations like {{user}}, {{user.username}}, {{request.user.username}}, etc. Also, in the message variable above, in signals_connectors.py, I have tried variations, with corresponding import statements.

I have also tried rendering templates with contexts set, and other variations that I have found on the web, eg:

finding the django-registration username variable

I keep getting something like this for an error:

global name 'user' is not defined

I think I have template context processing set up correctly, because I can use something like {{ user.username }} in another template and it works.

I have also tried correcting my import statements to include necessary objects, with no luck. I have tried most of what I can find on the web on this topic so I'm at a loss...

What am I missing?


Solution

  • I didn't realize this was so easy. Based on this post:

    Where should signal handlers live in a django project?

    I tried actually adding the user and request as arguments in the signal connector method and this worked:

    . . .
    
    @receiver(user_registered, dispatch_uid="common.signal_connectors.user_registered_handler")
    def user_registered_handler(sender, user, request, **kwargs):
    
    . . .
    

    Then, I used this in email template:

    {{ user }} has registered at example.com

    I probably over-thought this one but I am surprised no one stepped up and was able to help with this...