django 2 re_path表达式传递电子邮件验证令牌

时间:2018-09-04 22:33:31

标签: python django python-3.x django-urls django-2.0

我非常想在django 2 url中使用正则表达式。 一切似乎都是正确的,但是我遇到了404错误。

实际路径:

http://localhost:8000/user/activate/b'MjQ'/4zb-89a933fe70e0d12de725/

错误:

Using the URLconf defined in ec2django.urls, Django tried these URL        patterns, in this order:

user/
^user/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='activate']
health/
^static\/(?P<path>.*)$

The current path, user/activate/b'MjQ'/4zb-89a933fe70e0d12de725/, didn't match any of these.

urls.py

urlpatterns = [
   .....
   re_path(r'^user/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        user_activate, name='activate')
]

生成令牌:

            from django.utils.encoding import force_bytes
            from django.utils.http import urlsafe_base64_encode
            from django.template.loader import render_to_string
            from django.contrib.auth.tokens import default_token_generator

            message = render_to_string('email_account_activate.html', {
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': default_token_generator.make_token(user),
            })

验证:

try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    user = MyUser.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, MyUser.DoesNotExist):
    user = None
if user is not None and default_token_generator.check_token(user, token):
    user.is_active = True
    user.save()

URL或令牌格式是否有问题?感谢任何帮助。

0 个答案:

没有答案