我正在尝试使用context_processors从settings.py中转换一些可用于我的模板的配置。
我创建了一个这样的文件:
from django.conf import settings
def my_custom_var (request):
return {'MY_CUSTOM_VAR': settings.`MY_CUSTOM_PROP`}这是我在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',
],
},
},]当我尝试在html模板上使用{{ MY_CUSTOM_VAR }}时,一切正常。但是当我尝试在电子邮件密码重置模板(django/contrib/admin/templates/registration/password_reset_email.html),上使用它时,MY_CUSTOM_VAR的值是null。
这是我的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 %}有人知道出了什么问题吗?还有别的办法吗?
谢谢!
发布于 2016-03-17 03:13:21
罪魁祸首是PasswordResetForm类的send_mail方法。这里,render_to_string用于构建电子邮件正文:
class PasswordResetForm(forms.Form):
def send_mail(self, ...):
# ...
body = loader.render_to_string(email_template_name, context)
# ...如果希望它通过上下文处理器传递,则需要使用PasswordResetForm的自定义子类,在其中覆盖send_mail方法并为render_to_string提供额外的关键字参数context_instance,该参数必须是RequestContext实例:
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这适用于所有的模板渲染。只有RequestContext实例通过上下文处理器。
https://stackoverflow.com/questions/36022603
复制相似问题