如何在 Django 中实现电子邮件验证

问题描述 投票:0回答:1

完全被难住了!我使用控制台作为我的电子邮件后端。我最终在

False
中得到
token_generator.check_token
,结果是“令牌无效或过期”。当我导航到“http://localhost:8000/user/verify-email/?token=cgegv3-ec1fe9eb2cebc34e240791d72fb10d7d&[电子邮件受保护]”时,会显示在我的主页中

这是我的代码

from django.contrib.auth.tokens import PasswordResetTokenGenerator

class CustomPasswordResetTokenGenerator(PasswordResetTokenGenerator):
    pass

# Define a single instance of the token generator
token_generator = CustomPasswordResetTokenGenerator()
def verify_email(request):
    email = request.GET.get("email")
    token = request.GET.get("token")
    try:
        user = CustomUser.objects.get(email=email)
    except CustomUser.DoesNotExist:
        messages.error(request, "Invalid verification link.")
        return redirect("home")
    if token_generator.check_token(user, token):
        user.is_active = True
        user.save()
        messages.success(request, "Your email has been verified!")
        return redirect("sign_in")
    else:
        messages.error(request, "Invalid or expired token.")
        return redirect("home")
from django.core.mail import send_mail
from django.urls import reverse
from user_management.utils import token_generator


def send_verification_email(user, request):
    token = token_generator.make_token(user)
    verification_url = request.build_absolute_uri(
        reverse("verify_email") + f"?token={token}&email={user.email}"
    )
    send_mail(
        "Verify your email",
        f"Click the link to verify your email: {verification_url}",
        "[email protected]",
        [user.email],
        fail_silently=False,
    )

python django
1个回答
0
投票

最好的方法是使用 Django Allauth,您可以安全且简单地做任何事情,当然 Allauth 为您提供了许多其他选择。

© www.soinside.com 2019 - 2024. All rights reserved.