Trying to verify a user with Django email confirmation, however some user's are getting this error when they try to confirm their email

99封情书 提交于 2020-02-07 01:58:24

问题


I asked a variant of this question before, but realized I was very unclear. This is my attempt at doing a better job of explaining the issue.

I send a link to a user's email to confirm sign-up after they have registered for the site. However, a small proportion of users are getting the following error when they try to confirm their email.

Error:

TypeError/activate/{uidb64}/{token}/
error
'AnonymousUser' object is not iterable

I think the problem is that the activate function is not recognizing them. However, not sure how to make this activation link work if I send them back to the login page. Any ideas?

Do I need to add something like 'if not user.is_authenticated:' then send redirect to login? But, how do I come back to activate function? Login is general in my app to all situations.

Activate code:

try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
    user = None
if user is not None and account_activation_token.check_token(user, token):
    .... do something
else:
    return HttpResponse('Activation link is invalid!')

Here is where I create the email:

def activation_email(request):
    if request.user.is_authenticated:
        user=request.user
        message = render_to_string('email.html', {
                'user':user,
                'token':account_activation_token.make_token(user),
                'uid':urlsafe_base64_encode(force_bytes(user.pk)),
        })
        ....send mail
    else:
        return redirect('somewhere_else')

EDIT>: It's failing when I try to update my model with the email verification info:

if user is not None and account_activation_token.check_token(user, token):
      object, created = User_Profile.objects.get_or_create(
            user=request.user,
            ## This is where it fails
            email_validated=True,
        )

回答1:


I think your approach for activating user is wrong here. I don't think you would need to activate users who are authenticated. Because if they are authenticated, it means they are active users, hence they don't need activation.

And regarding the error, when users are activated, you got the user information here:

if user is not None and account_activation_token.check_token(user, token):  # <-- in user variable

So why not use it in the next section(as per comments):

obj, created = User_Profile.objects.get_or_create(
    user=user,  # <-- here
    email_validated=True,
)


来源:https://stackoverflow.com/questions/59939607/trying-to-verify-a-user-with-django-email-confirmation-however-some-users-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!