所以我正在制作一个电子邮件验证系统,但urlsafe_base64_decode返回的是None而不是pk。
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
subject = 'Activá tu mail'
current_site = get_current_site(request)
encoded_uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()
message = render_to_string('firstpage/acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': encoded_uid,
'token': account_activation_token.make_token(user),
})
to_email = form.cleaned_data['email']
from_email = 'backend_email@gmail.com'
send_mail(subject, message, from_email, [to_email])
user.set_password(password)
user.save()
user_profile=UserProfile.objects.create(user=user)
#returns user objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('/')
return render(request, self.template_name, {'form': form})
然后用户单击链接,并将其重定向到此功能
def activate(request, uidb64=None, token=None):
uid = urlsafe_base64_decode(uidb64).decode()
user = User.objects.get(pk=uid)
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
# return redirect('home')
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
else:
print(user)
print(uid)
print(account_activation_token.check_token(user, token))
return HttpResponse('Activation link is invalid!')
uidb64返回与urlsafe_base64_encode(force_bytes(user.pk))。decode()相同,但urlsafe_base64_decode(uidb64).decode()返回None。
我正在使用Django 2.1。
答案 0 :(得分:0)
您需要使用force_text
返回代表任意对象的str对象并保留惰性对象,请使用-force_text(urlsafe_base64_decode(uidb64))
有关更多参考,请访问文档
-https://docs.djangoproject.com/en/2.1/ref/utils/#django.utils.encoding.force_text
希望这会对您有所帮助。