Search code examples
djangodjango-rest-auth

How to customize django rest auth email context


Similar to this question How to customize django rest auth password reset email content/template I would like to customize password reset (and other) emails automatically send by django rest auth. It perfectly works to use custom email templates with an custom serializer:

class CustomPasswordResetSerializer(PasswordResetSerializer):
    def get_email_options(self):
        return {
            'domain_override': settings.FRONTEND_URL,
            'email_template_name': 'registration/custom_reset_email.txt',
            'html_email_template_name': 'registration/custom_reset_email.html',
        }

But additionally to customized templates I want to add custom context. Is there a simple way to do it?


Solution

  • The PasswordResetSerializer uses the PasswordResetForm from django.contrib.auth.forms. The save() method of the PasswordResetForm accepts a parameter extra_email_context. So all you need to do is add extra_email_context to the dictionary your return:

    def get_email_options(self):
        extra_context = {...}  # your extra context parameters
        return {
                'domain_override': settings.FRONTEND_URL,
                'email_template_name': 'registration/custom_reset_email.txt',
                'html_email_template_name': 'registration/custom_reset_email.html',
                'extra_email_context': extra_context
            } 
    

    Just make sure your extra_context doesn't override existing keys: email, token, domain, site_name, user, uid and protocol are already in use.