gpt4 book ai didi

python - Django password_reset 是否支持 html 电子邮件模板?

转载 作者:太空狗 更新时间:2023-10-29 21:29:52 24 4
gpt4 key购买 nike

在我看来,django 仅支持开箱即用的密码重置电子邮件的纯文本消息。我如何为此目的使用 html 模板?

最佳答案

以下是您如何进行覆盖:

网址.py

url(r'^user/password/reset/$', 
'YOUR_APP.views.password_reset',
{'post_reset_redirect' : '/#/login?resetemail=true'},
name="password_reset"),

View .py

from django.contrib.auth.views import password_reset as django_password_reset
from YOUR_APP.forms import CustomPasswordResetForm

def password_reset(*args, **kwargs):
"""
Overriding the Email Password Resert Forms Save to be able to send HTML email
"""
kwargs['password_reset_form'] = CustomPasswordResetForm
return django_password_reset(*args, **kwargs)

表单.py

from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.tokens import default_token_generator

class CustomPasswordResetForm(PasswordResetForm):
"""
Overriding the Email Password Resert Forms Save to be able to send HTML email
"""
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator, request=None, email_subject_name='registration/password_reset_subject.txt', **kwargs):
from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
from django.template.loader import render_to_string
from django.contrib.sites.models import get_current_site
from django.utils.http import int_to_base36

for user in self.users_cache:
if not domain_override:
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
else:
site_name = domain = domain_override

c = {
'email': user.email,
'domain': domain,
'site_name': site_name,
'uid': int_to_base36(user.id),
'user': user,
'token': token_generator.make_token(user),
'protocol': use_https and 'https' or 'http',
}
render = render_to_string(email_template_name, c)
render_subject = render_to_string(email_subject_name, c)

msg = EmailMultiAlternatives(render_subject, strip_tags(render), None, [user.email])
msg.attach_alternative(render, "text/html")
msg.send()

关于python - Django password_reset 是否支持 html 电子邮件模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com