如何正确修改password-reset-email模板



这行代码负责发送包含密码重置链接的电子邮件。

path('accounts/password-reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),

然而,电子邮件看起来完全枯燥,在阅读时很难区分重要的部分。

为了吸引用户的注意力,更好地引导他们,我想在邮件正文中添加一些风格。

可以通过以下几行添加自定义模板到电子邮件:

...
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/password-reset/', auth_views.PasswordResetView.as_view(html_email_template_name='registration/password_reset_email.html'), name='password_reset'),
...

问题是电子邮件中的重置链接由一个uidb64值和一个令牌组成,例如:

localhost:8000/password-reset/calculated_uidb64/calculated_token

将这些值传递给password_reset_email.html的自定义模板的正确方法是什么?

在django PasswordResetView中使用自定义邮件模板之前,有几件事你需要知道。

  1. django使用registration/password_reset_email.html作为邮件内容的默认文件来重置密码,除非你在PasswordResetViewhtml_email_template_name参数值中明确定义/提供它。

  2. Django允许email模板中的jinja模板根据你的需求来修改它。

  3. PasswordResetView提供了开箱即用的密码重置视图所需的上下文。例如用户实例来填写任何用户详细信息、站点名称、令牌等。

这是一个通过django模板使用context的邮件模板示例。

{% autoescape off %}
You're receiving this e-mail because you requested a password reset for your user account at {{ site_name }}.
Please go to the following page and choose a new password:
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}
{% endblock %}
Your username, in case you've forgotten: {{ user.username }}
Thanks for using our site!
The {{ site_name }} team.
{% endautoescape %}

上述模板中使用(或可以使用)的上下文如下:

email: An alias for user.email
user: The current User, according to the email form field. Only active users are able to reset their passwords (User.is_active is True).
site_name: An alias for site.name. If you don’t have the site framework installed, this will be set to the value of request.META['SERVER_NAME']. For more on sites, see The “sites” framework.
domain: An alias for site.domain. If you don’t have the site framework installed, this will be set to the value of request.get_host().
protocol: http or https
uid: The user’s primary key encoded in base 64.
token: Token to check that the reset link is valid.

注:由于user是用户模型实例,其他值如user。id、用户。Contact_number也可以在email模板中使用。

有用的资源:

  1. 我强烈推荐这篇关于Django:重置密码(使用内部工具)的文章
  2. django官方文档,描述有用的选项和上下文。
  3. django库中的代码,用于深入了解PasswordResetVieww的工作原理。

最新更新