【问题标题】:Custom activation email not working in Django自定义激活电子邮件在 Django 中不起作用
【发布时间】:2020-02-10 15:45:06
【问题描述】:

目标是带有激活令牌的自定义电子邮件。目前,此设置可用于点击进入 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 具有以下消息,activation.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>

【问题讨论】:

    标签: django html-email


    【解决方案1】:

    您正在尝试在kwargs 中使用uid reverse,但您的网址被定义为期望uidb64

    怎么样:

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

    【讨论】:

    • 感谢这解决了反向问题,但链接仍然不显示。
    • 您将 url 传递给 HTML 上下文。在您的激活模板中使用它。 {% if url %} {{ url }} {% endif %} 等
    • 另外,您的模板不一致。他们在不同的背景下做同样的事情。改变它怎么样?
    • 抱歉发帖后改了,我的模板是一致的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 2014-05-01
    • 2011-02-23
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多