【问题标题】:Reseting URL in Django through views.py通过views.py在Django中重置URL
【发布时间】:2018-04-07 17:10:46
【问题描述】:

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

我有一个问题,我生成了一个用户激活链接 URL 并向用户发送邮件。

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

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

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'),

【问题讨论】:

  • 登录后你应该重定向。
  • @DanielRoseman 一旦用户点击链接,我想用干净的 url 登录并将他重定向到特定页面。目前它确实被重定向但在 url 中有激活令牌,这会在访问其他页面时导致问题
  • 不,目前这里根本没有重定向 - 您已将其注释掉并用 render 调用替换它。
  • @DanielRoseman 是的,我正在寻找更多重定向的好方法 HttpResponseRedirect 是一种硬编码,所以我评论了它

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


【解决方案1】:

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

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'),

做相应的小改动...

【讨论】:

    猜你喜欢
    • 2016-04-03
    • 2017-05-08
    • 1970-01-01
    • 2020-11-09
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2012-04-12
    相关资源
    最近更新 更多