使用电子邮件进行注册,Django 2.0

D. *_*ake -1 python django

我只是一个初学者,所以我在做第一个项目时遇到了一些问题。我在视图中有代码:

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()
        current_site = get_current_site(request)
        mail_subject = '?????????'
        message = render_to_string('acc_active_email.html', {
            'user': user,
            'domain': current_site.domain,
            'uid':urlsafe_base64_encode(force_bytes(user.pk)),
            'token':account_activation_token.make_token(user),
        })
        print(message) # ????? ? ?????? ????? ????????? ?????????

        to_email = form.cleaned_data.get('email')
        email = EmailMessage(
                    mail_subject, message, to=[to_email]
        )
        email.send()
        return HttpResponse('??????????, ??????????? ????? ??????????? ?????')
else:
    form = SignupForm()
return render(request, 'signup.html', {'form': form})


def activate(request, uidb64, token):
    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):
        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:
        return HttpResponse('Activation link is invalid!')
Run Code Online (Sandbox Code Playgroud)

这段代码来自网址:

from . import views
from django.urls import path

urlpatterns = [
    path('', views.signup, name='signup'),
    path('activate/?P<uidb64>[0-9A-Za-z_\-]+/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        views.activate, name='activate'),
]
Run Code Online (Sandbox Code Playgroud)

问题是我总是在电子邮件中收到无效的URL。我认为这与新的“路径”功能有关,可以使用的是

<int:uidb64>
Run Code Online (Sandbox Code Playgroud)

但不是很确定。感谢您的帮助!

Ala*_*air 5

您不能像[0-9A-Za-z_\-]+使用时那样使用正则表达式path()。如果要使用正则表达式,请使用re_pathurl()与旧版本的Django相同)。

使用时path(),可以使用内置的路径转换器之一。您不能使用<int:uidb64>,因为uidb可以包含A-Za-z,连字符和下划线,而不仅仅是数字。

对于您uidb64token,我认为slug最适合Django中包含的路径转换器。

path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'),
Run Code Online (Sandbox Code Playgroud)

这将匹配您的正则表达式不允许的子段和标记,但这不是问题,只要您的check_token方法返回False这些无效值并且不会引发错误即可。