首页 > 解决方案 > 试图让电子邮件激活工作,但它失败了

问题描述

试图让本教程在我的应用程序中工作: https ://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef

无论我是否包含 .decode(),“uid”都会失败。

message = render_to_string('premium/activation_email.html', {'user':user,

 'token': account_activation_token.make_token(user),
 #this fails both with the .decode() and without
 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
            })
mail_subject = 'Activate your membership account.'
send_mail(mail_subject, message,'info@mysite.com', [request.user.email])

这是两个错误:

Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name

然后,如果我添加 .decode():

str object has no attribute decode()

这是我的带有激活标签的 urls.py:

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

我的激活视图与教程中的完全相同

标签: djangodjango-email

解决方案


由于Django >2.2urlsafe_base64_encode将返回字符串而不是字节字符串,因此您不必再调用.decode()urlsafe_base64_encode

在 Django 2.2 中更改:在旧版本中,它返回一个字节串而不是一个字符串。

遵循您嵌入问题的指南,问题Reverse for 'activate' not found来自于此:

{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}

有两种情况可能导致此问题:

  1. 你的路径:
path('activate/<uidb64>/<token>/', views.activate, 'activate'),

你应该这样命名你的视图:

path('activate/<uidb64>/<token>/', views.activate, name='activate'),
  1. 如果您的视图停留在站点级别(在 django 应用程序 url 中,而不是在 ROOT_URLS 中),那么您可能需要在您的insideapp_name = 'your_app_name'顶部添加。然后在您的邮件模板中:urlpatternsurls.py
{% autoescape off %}
Hi {{ user.username }},
Please click on the link to confirm your registration,
http://{{ domain }}{% url 'your_app_name:activate' uidb64=uid token=token %}
{% endautoescape %}

希望有帮助!


推荐阅读