Django:在不使用“网站"框架的情况下,在“模板/电子邮件"中显示网站名称 [英] Django: Display website name in Template/Emails without using Sites framework
问题描述
我想在Django模板中呈现我的网站名称. Django在Sites状态下的文档:
如果您的单个Django安装为多个站点提供支持,请使用它并且您需要以某种方式区分这些网站.
我的django应用程序没有.我知道我可以仍然使用它,但这似乎有点过头了.我只想在ANY模板中提取带有我的网站名称(!=域)的变量.我也不想在视图中传递它,因为这似乎还不够干.
编写自定义处理器似乎很简单,但是由于某些原因,这些变量在django-registration发送的.txt电子邮件中不可用(而其他变量肯定是,所以我想并非不可能)./p>
TIA
被要求包含无效代码:
processors.py:
def get_website_name(request):website_name ='SomeWebsite'返回{'mysite_name':website_name}
已成功包含在settings.py的 context_processors
中.它可以在常规"模板中很好地工作,但在电子邮件中却不能.
这是我在 change_email_view
内发送电子邮件的方式:
msg_plain = render_to_string('email_change_email.txt',上下文)msg_html = render_to_string('email_change_email.html',上下文)发送邮件(电子邮件更改请求",msg_plain,'我的电子邮件',[profile.pending_email],html_message = msg_html,)
进一步的问题是django-regitration进一步将其中的某些视图抽象了:因此,当用户注册,想要重置密码等时,我什至无权访问视图.
基于Django's own docs on Sites state:
Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way.
My django app doesn't. I know I can still use it, but it seems like an overkill. I just want to pull a variable with my website's name (!= domain) in ANY template. I don't want to pass it in views either because that doesn't seem DRY enough.
Writing a custom processor seemed like a simple-enough option, but for some reason these variables aren't available in the .txt emails django-registration sends (while other variables definitely are, so I guess it's not impossible).
TIA
Edit: was asked to include code that doesn't work:
processors.py:
def get_website_name(request):
website_name = 'SomeWebsite'
return {'mysite_name': website_name}
Included successfully in context_processors
in settings.py. It works nicely in "regular" templates, but not in emails.
Here's how I'm sending the emails, inside a change_email_view
:
msg_plain = render_to_string('email_change_email.txt', context)
msg_html = render_to_string('email_change_email.html', context)
send_mail(
'Email change request',
msg_plain,
'my@email',
[profile.pending_email],
html_message=msg_html,
)
A further problem is that django-regitration further abstracts some of those views away: so when a user registers, wants to reset a password, etc...I don't even have access to the views.
Based on Django custom context_processors in render_to_string method you should pass the request to render_to_string
.
msg_plain = render_to_string('email_change_email.txt', context, request=request)
msg_html = render_to_string('email_change_email.html', context, request=request)
这篇关于Django:在不使用“网站"框架的情况下,在“模板/电子邮件"中显示网站名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!