自定义激活电子邮件在 Django 中不起作用



目标是使用激活令牌自定义电子邮件。目前,此设置适用于单击进入 URL,但不适用于激活链接。第一个模板是 html 内容,第二个模板是消息内容。

from_email = '<info@domain>'
#this is the custom template
htmly = get_template('activation.html')
#this is just the template of the message
message = render_to_string('activation_email.html', {
'user':user,
'token': account_activation_token.make_token(user),
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
})
reverse(
'activate',
kwargs={
'token':force_text(urlsafe_base64_encode(force_bytes(user.pk))),
'uidb64':urlsafe_base64_encode(force_bytes(user.pk))
})
subject = 'Email activation'
html_content = htmly.render(d) 
msg = EmailMultiAlternatives(subject, message, from_email, [request.user.email])
msg.attach_alternative(html_content, "text/html")
msg.send()

我得到的错误是:

django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments

如果我尝试将其作为一个模板发送,即消息和消息中的自定义 html。我的 html 呈现为字符串。

这是我尝试发送的电子邮件。activation_email具有以下消息和激活.html具有自定义电子邮件 html 模板。

activation_email.html

{% autoescape off %}
Hi {{ user.username }},
Email confirmation:
http://domain{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}

url.py

path('activate/<uidb64>/<token>/', views.activate, name='activate'),

编辑:下面的反向修复了此错误,但仍然没有修复URL。您无法单击。

如果有帮助,这是另一个电子邮件模板。

<h3>Hi <strong>{{ username }}</strong>,</h3>
<p> Email Confirmation</p>
<a class="btn btn-primary" href="http://domain{% url 'activate' uidb64=uidb64 token=token %}">Email Activation</a>

您正在尝试reversekwargs中的uid,但您的URL被定义为预期uidb64

怎么样:

reverse(
'activate',
kwargs={
'token':force_text(urlsafe_base64_encode(force_bytes(user.pk))),
'uidb64':urlsafe_base64_encode(force_bytes(user.pk))
})