[Answered ]-How to add context to the activation_email.txt in Django

2👍

That app does not trivially expose hooks to add more context or change the context type used to build the email – your best bet is to subclass its RegistrationProfile class (which actually builds and sends the email message) and at least the RegistrationView class-based view, then make sure your urls.txt is calling your view subclass instead. Something like:

from registration.models import RegistrationProfile
from django.template import RequestContext

class VerboseRegistrationProfile(RegistrationProfile):

    def send_activation_email(self, site):
        ctx_dict = {'activation_key': self.activation_key,
                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                    'site': site,
        subject = render_to_string('registration/activation_email_subject.txt',
                                   ctx_dict, context=RequestContext())
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())

        message = render_to_string('registration/activation_email.txt',
                                   ctx_dict, context=RequestContext())

        self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)

Then your view:

from myreg.models import VerboseRegistrationProfile
from registration.backends.default import RegistrationView

class VerboseRegistrationView(RegistrationView):

    def register(self, request, **cleaned_data):
        username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = VerboseRegistrationProfile.objects.create_inactive_user(username, email,
                                                                           password, site)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user

To avoid future maintenance problems in case you ever further specialize your RegistrationProfile subclass you’d probably also want to override ActivationView as well, but it’s not strictly necessary.

Leave a comment