美文网首页《Django By Example》
配置password_reset_email支持html渲染

配置password_reset_email支持html渲染

作者: 盗花 | 来源:发表于2018-12-19 21:15 被阅读1次

Django自带密码重置功能,在配置过程中,要用到password_reset_email.html文件,功能是在重置密码邮件中显示相关内容。示例如下:
1.配置urls.py文件

from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.urls import reverse, reverse_lazy
from . import views

urlpatterns = [
    url(r'^password-reset/$', auth_views.password_reset, {
        'email_template_name': 'registration/password_reset_email.html',
        'post_reset_redirect': reverse_lazy('account:password_reset_done')
    }, name='password_reset'),
    url(r'^password-reset-done', auth_views.password_reset_done, name='password_reset_done'),
]

2.配置password_reset_email.html文件

<p>
    You're receiving this email because you requested a password reset for your account at 大青呱呱.com
</p>
<p>Please go to the following page and choose a new password:</p>
<a href="{{ protocol }}://{{ domain }}{% url 'account:password_reset_confirm' uidb64=uid token=token %}">{{ protocol }}://{{ domain }}{% url 'account:password_reset_confirm' uidb64=uid token=token %}</a>
<p>Your username, in case you've forgotten:{{ request.user.get_username }}</p>
<p>Thanks for using our site!</p>
<p>大青呱呱.com!!!</p>

其他配置从略。结果,在我接收到的邮件中,显示的内容如下:


从图中看出,在password_reset_email.html中设置的各种html标签不起作用,完全就是以普通字符显示。这肯定不符合我的要求。

网上一番搜寻后,找到答案,原来在auth_views.password_reset的源码中,还有一个html_email_template_name参数,默认为None,如下图所示:


所以,重新配置urls.py,将html_email_template_name指向password_reset_email.html,如下所示:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.urls import reverse, reverse_lazy
from . import views

urlpatterns = [
    url(r'^password-reset/$', auth_views.password_reset, {
        'html_email_template_name': 'registration/password_reset_email.html',
        'post_reset_redirect': reverse_lazy('account:password_reset_done')
    }, name='password_reset'),
    url(r'^password-reset-done', auth_views.password_reset_done, name='password_reset_done'),
]

此时邮件的显示效果如下:


大功告成。
参考链接:https://stackoverflow.com/questions/21793829/how-to-make-django-password-reset-email-beautiful-html

相关文章