【发布时间】:2011-11-09 05:47:43
【问题描述】:
我正在创建一个 django 项目。但是,我遇到了一个小问题。我的 urls.py 看起来像这样
url(r'^login/(?P<nextLoc>)$', 'Home.views.login'),
url(r'^logout/$', 'Home.views.logout'),
我在 Home 应用中的 views.py 如下:
def login(request,nextLoc):
if request.method == "POST":
form = AuthenticationForm(request.POST)
user=auth.authenticate(username=request.POST['username'],password=request.POST['password'])
if user is not None:
if user.is_active:
auth.login(request, user)
return redirect(nextLoc)
else:
error='This account has been disabled by the administrator. Contact the administrator for enabling the said account'
else:
error='The username/password pair is incorrect. Check your credentials and try again.'
else:
if request.user.is_authenticated():
return redirect("/profile/")
form = AuthenticationForm()
error=''
return render_to_response('login.html',{'FORM':form,'ERROR':error},context_instance=RequestContext(request))
def logout(request):
auth.logout(request)
return redirect('/')
现在当我进入登录页面时,它按预期打开了。提交表单后,我收到一条错误消息,提示找不到模块 url。经过一番挖掘,我注意到重定向(“/”)实际上转换为http://localhost/login/,而不是http://localhost/。注销时也会发生同样的情况,即它尝试打开 url http://localhost/logout/ 而不是 http://localhost/。基本上,当打开的页面是http://localhost/login 时,redirect('/') 将 / 添加到当前 url 的末尾,瞧——我得到了一个我没想到的 url——http://localhost/login/。我无法使用重定向将其重定向到站点的根目录。
请帮我解决这个问题,如果可能的话,请解释一下 Django 这种不合理行为的原因
【问题讨论】:
-
您尝试过 HttpResponseRedirect 吗? from django.http import HttpResponseRedirect def logout(request): return HttpResponseRedirect("/")
-
你的 urls.py 的其余部分在哪里? “/”对应什么视图?
标签: python django authentication redirect