django 中电子邮件激活失败

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

我如何发送激活电子邮件

        current_site = get_current_site(request)
        email_subject = 'confirm your email !'

        message2= render_to_string('authentication/emailConfirmation.html',{     
            'name':user.first_name + user.last_name,
            'domain':current_site.domain,
            'uid':urlsafe_b64encode(force_bytes(user.pk)),
            'token':generate_token.make_token(user)})
        
        email= EmailMessage(
          email_subject,
          message2,
          settings.EMAIL_HOST_USER,
          [user.email],

        )
        email.send()
        

激活视图

from django.core.mail import send_mail ,EmailMessage
from django.http import Http404, HttpResponse
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes , force_str
from django.utils.http import urlsafe_base64_decode
from . tokens import generate_token

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):
        raise Http404("Invalid activation link")

    if generate_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        messages.success(request, "Your account has been activated!")
        return redirect(reverse('index'))
    else:
        raise ValidationError("Invalid activation link")```

the token.py file

从django.contrib.auth.tokens导入PasswordResetTokenGenerator 从六个导入text_type

类 TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(自身,用户,时间戳): return (text_type(user.pk) + text_type(timestamp))

generate_token = TokenGenerator()```

确认电子邮件模板

{% autoescape off %}


Confirmation Link: http://{{ domain }}{% url 'activate' uidb64=uid token=token %}

{% endautoescape %}

每当我点击确认链接时,它都会自动失败

django email django-views activation
1个回答
0
投票

看起来你可能会从像

"b'MzI='"
这样的URL中获取uidb64值,所以它会像这样解码:

uidb64 = "b'MzI='"
base64.b64decode(val[2:-1])
© www.soinside.com 2019 - 2024. All rights reserved.