Reputation: 55
how im sending the activation email
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()
the activate view
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
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()```
the confirmation email template
{% autoescape off %}
Confirmation Link: http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}
whenever i click on the confirmation link it automatically fails
Upvotes: 1
Views: 46
Reputation: 55
Well, the problem lay in the encoding process. Instead of using urlsafe_b64encode
from the base64
module, which is related to Python, the appropriate function to use in the context of Django is urlsafe_base64_encode
from django.utils.http
. Since urlsafe_b64encode
is a Python function, while urlsafe_base64_encode
is specifically tailored for Django.
Upvotes: 0
Reputation: 476
It seems you might get the uidb64 value from the URL like "b'MzI='"
so it would be decoded like this:
uidb64 = "b'MzI='"
base64.b64decode(val[2:-1])
Upvotes: 0