试图让电子邮件激活工作,但失败了

Trying to get email activation to work, but it fails

尝试让本教程在我的应用程序中运行: 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'),

我的激活视图与教程中的完全一样

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

Changed in Django 2.2: In older versions, it returns a bytestring instead of a string.

按照您在问题中嵌入的指南进行操作,问题 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 中),那么您可能需要在 urlpatterns 中的 urlpatterns 之上添加 app_name = 'your_app_name' 20=]。然后在您的邮件模板中:
{% 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 %}

希望对您有所帮助!