通过views.py

时间:2017-10-26 10:42:33

标签: python django python-3.x url redirect

我正在使用Python 3.6,Django 1.11和Salesforce NPSP作为我的后端。

我遇到了问题,我在其中生成了用户激活链接网址&向用户发送邮件。

一旦用户点击&确认,他将登录&允许使用该应用程序。

我为邮件激活生成的网址如下所示,其中包含令牌值

localhost:8080/naka/activation/abg479843fiuegf/hfduige433274

一旦用户点击上面的网址,他就会被带到主页

localhost:8080/naka/activation/abg479843fiuegf/hfduige433274/home.html

我希望将上面的网址重置为

localhost:8080/naka/home.html

原因是访问我的其他页面很容易,比如

localhost:8080/naka/aboutus.html
localhost:8080/naka/contactus.html

等等

我添加了我的view.py文件,其中包含激活方法

def activate(request, uidb64, token):

context=locals()
try:
    uid = force_text(urlsafe_base64_decode(uidb64))
    user = uid

except(TypeError, ValueError, OverflowError):
    user = None

if user is not None and account_activation_token.check_token(user, token):
    user.is_active = True
    user.save()
    login(request, user, backend='django.contrib.auth.backends.ModelBackend')
    return render(request,'home/home.html',context)
    #return HttpResponseRedirect('http://localhost:8000/naka/home.html')
else:
    return HttpResponse('Activation link is invalid!')

我还在urls.py文件中添加了与激活相关的一行

url(r'^naka/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'),

1 个答案:

答案 0 :(得分:0)

通过以下方式更改您的激活方法: -

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.profile.email_confirmed = True
    user.save()
    login(request, user)
    return redirect('home')
else:
    return render(request, 'account_activation_invalid.html')

您的网址应该是: -

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

相应地做一些小改动......