如何正确更改 Django 密码重置电子邮件的模板

Xfc*_*ce4 5 html python email django templates

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

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'),
...
Run Code Online (Sandbox Code Playgroud)

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

localhost:8000/password-reset/calculated_uidb64/calculated_token
Run Code Online (Sandbox Code Playgroud)

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

小智 10

在 django PasswordResetView 中使用自定义电子邮件模板之前,您需要了解以下几件事。

\n
    \n
  1. django 使用registration/password_reset_email.html电子邮件内容的默认文件来重置密码,除非您在PasswordResetView\ 的html_email_template_name参数值中明确定义/提供了它。

    \n
  2. \n
  3. Django 允许电子邮件模板中的 jinja 模板根据您的要求进行修改。

    \n
  4. \n
  5. PasswordResetView 提供开箱即用的密码重置视图所需的即用上下文。例如用于填写任何用户详细信息、site_name、令牌等的用户实例。

    \n
  6. \n
\n

以下是通过 django 模板使用上下文的电子邮件模板示例。

\n
{% autoescape off %}\nYou\'re receiving this e-mail because you requested a password reset for your user account at {{ site_name }}.\n\nPlease go to the following page and choose a new password:\n{% block reset_link %}\n{{ protocol }}://{{ domain }}{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}\n{% endblock %}\n\nYour username, in case you\'ve forgotten: {{ user.username }}\n\nThanks for using our site!\n\nThe {{ site_name }} team.\n\n{% endautoescape %}\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
email: An alias for user.email\nuser: The current User, according to the email form field. Only active users are able to reset their passwords (User.is_active is True).\nsite_name: An alias for site.name. If you don\xe2\x80\x99t have the site framework installed, this will be set to the value of request.META[\'SERVER_NAME\']. For more on sites, see The \xe2\x80\x9csites\xe2\x80\x9d framework.\ndomain: An alias for site.domain. If you don\xe2\x80\x99t have the site framework installed, this will be set to the value of request.get_host().\nprotocol: http or https\nuid: The user\xe2\x80\x99s primary key encoded in base 64.\ntoken: Token to check that the reset link is valid.\n
Run Code Online (Sandbox Code Playgroud)\n

注意:由于 user 是用户模型实例,因此电子邮件模板中还可以使用其他值,例如 user.id、user.contact_number。

\n

有用的资源:

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