Edinilton
Edinilton

Reputation: 31

Django - context_processors

I´m trying to use context_processors to turn some configurations from settings.py, avaliable to my templates.

I created a file with like this:

from django.conf import settings
def my_custom_var (request):
    return {'MY_CUSTOM_VAR': settings.`MY_CUSTOM_PROP`}

This is my templates configuration on settings.py:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.template.context_processors.i18n',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            'my_app.py_file.my_custom_var',
        ],
    },
},]

When I try to use {{ MY_CUSTOM_VAR }}, on my html templates, everything works fine. But when I try to use this on email password reset template (django/contrib/admin/templates/registration/password_reset_email.html), the value of MY_CUSTOM_VAR is null.

This is my password_reset_email.html:

{% load i18n %}{% autoescape off %}
{% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %}

{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}

MY_CUSTOM_VAR: {{ MY_CUSTOM_VAR }}

{% endblock %}
{% trans "Your username, in case you've forgotten:" %} {{ user.get_username }}

{% trans "Thanks for using our site!" %}
{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
{% endautoescape %}

Anyone knows what´s wrong? There are another way to do it?

Thanks!

Upvotes: 2

Views: 1485

Answers (1)

user2390182
user2390182

Reputation: 73470

The culprit is the send_mail method of the PasswordResetForm class. Here, render_to_string is used to build the email body:

class PasswordResetForm(forms.Form):
    def send_mail(self, ...):
        # ...
        body = loader.render_to_string(email_template_name, context)
        # ...

If you want this to pass through your context processors, you need to use a custom subclass of PasswordResetForm where you you override the send_mail method and provide render_to_string with an additional keyword argument context_instance which must be a RequestContext instance:

        body = loader.render_to_string(
            email_template_name, context,
            context_instance=RequestContext(request)
        ) 
        # you might have to pass the request from the view 
        # to form.save() where send_mail is called

This holds for all template rendering. Only RequestContext instances pass through context processors.

Upvotes: 2

Related Questions