我正在尝试通过电子邮件激活用户,电子邮件可以正常工作,编码也可以正常工作,我使用了Django1.11的一种方法,这个方法之前成功地运行过。
在Django1.11中,以下内容成功解码为28,其中uidb64 = b'Mjg'
force_text(urlsafe_base64_decode(uidb64))
在 Django 2(版本号为 2.0.0 final)中,上述代码的解码功能不可用并会导致错误。
django.utils.encoding.DjangoUnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 1: invalid continuation byte. You passed in b'l\xc8\xe0' (<class 'bytes'>)
我也发表一下我的看法,以防万一。
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
# auth_login(request, user)
message = render_to_string('user_activate_email.html', {
'user': user,
'domain': Site.objects.get_current().domain,
'uidb64': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
mail_subject = 'Activate your blog account.'
to_email = form.cleaned_data.get('email')
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.info(
request, 'Activation link has been sent to your email!')
# return redirect('home')
return render(request, 'index.html')
else:
form = SignUpForm()
return render(request, 'user_action.html', {'form': form})
def activate(request, uidb64, token):
try:
import pdb;
pdb.set_trace()
uid = urlsafe_base64_decode(uidb64).decode()
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.refresh_from_db()
user.is_active = True
user.save()
auth_login(request, user)
messages.info(request, 'Your account has been activated successfully!')
return redirect('events:home')
else:
messages.info(
request, 'Activation link is invalid or has been activated')
return redirect('events:home')
PS:在我与CBV合作之前,这只是一次试验。
编辑:包括回溯信息。
System check identified no issues (0 silenced).
December 15, 2017 - 05:51:01
Django version 2.0, using settings 'event_management.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
> /home/vipinmohan/django2-0/event/event_management/users/views.py(88)activate()
-> uid = urlsafe_base64_decode(uidb64).decode()
(Pdb) n
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 1: invalid continuation byte
> /home/vipinmohan/django2-0/event/event_management/users/views.py(88)activate()
-> uid = urlsafe_base64_decode(uidb64).decode()
(Pdb) n
> /home/vipinmohan/django2-0/event/event_management/users/views.py(90)activate()
-> except(TypeError, ValueError, OverflowError):
(Pdb) n
> /home/vipinmohan/django2-0/event/event_management/users/views.py(91)activate()
-> user = None
(Pdb)