因此,我正在學習在使用 Django 注冊帳戶時創建確認電子郵件地址。
這是我的 urls.py:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('sign-up', views.sign_up, name='sign-up'),
path('sign-in', views.sign_in, name='sign-in'),
path('sign-out', views.sign_out, name='sign-out'),
path('activate/<uidb64>/<token>/', views.activate, name='activate'),
]
我有這個 email_confirmation.html 模板:
{% autoescape off %}
Hello {{ name }}!
Please confirm your email by clicking on the following link.
http://{{ domain }}{% url 'activate' uid64=uid token=token %}
{% endautoescape %}
令牌.py:
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from six import text_type
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
text_type(user.pk) text_type(timestamp)
)
generate_token = TokenGenerator()
這是我的 views.py:
def sign_up(request):
# other code (didnt specify in this question)
# Confirmation email
current_site = get_current_site(request)
email_subject = "Email confirmation of My Page"
confirmation_message = render_to_string('email_confirmation.html', {
'name': user.first_name,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': generate_token.make_token(user),
})
email = EmailMessage(
email_subject,
confirmation_message,
settings.EMAIL_HOST_USER,
[user.email],
)
email.fail_silently = True
email.send()
return redirect('sign-in')
return render(request, "authentication/sign-up.html")
def activate(request, uidb64, token):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and generate_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return redirect("home")
else:
return render(request, 'activation_failed.html')
最后,我收到此錯誤:
NoReverseMatch at /sign-up
Reverse for 'activate' with keyword arguments '{'uid64': 'OA', 'token': 'ayjcvq-ae5426fe52cc9f8f5a545615ac9ef1c1'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[^/] )/(?P<token>[^/] )/\\Z']
Request Method: POST
Request URL: http://127.0.0.1:8000/sign-up
Django Version: 4.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'activate' with keyword arguments '{'uid64': 'OA', 'token': 'ayjcvq-ae5426fe52cc9f8f5a545615ac9ef1c1'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[^/] )/(?P<token>[^/] )/\\Z']
我的問題是,為什么我會收到這個錯誤,你們有什么解決辦法嗎?謝謝
uj5u.com熱心網友回復:
將您的網址路徑更改為
path('activate/<uid64>/<token>/', views.activate, name='activate'),
uj5u.com熱心網友回復:
您的 url 引數是activate/<uidb64>/<token>/. 引數名稱是uidb64但您uid64在電子郵件模板中寫的。只需像這樣將 uid64 替換為 uidb64
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
或者你可以寫
http://{{ domain }}{% url 'activate' uid token %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/400926.html
