Roh*_*tra 7 python authentication django redirect
我正在创建一个django项目.但是,我遇到了一个小小的打嗝.我的urls.py看起来像这样
url(r'^login/(?P<nextLoc>)$', 'Home.views.login'),
url(r'^logout/$', 'Home.views.logout'),
Run Code Online (Sandbox Code Playgroud)
我在家庭应用程序中的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('/')
Run Code Online (Sandbox Code Playgroud)
现在,当我进入登录页面时,它正按预期打开.提交表单后,我收到一条错误消息,指出它无法找到模块URL.在挖了一下之后,我注意到重定向("/")实际上转化为http://localhost/login/而不是http://localhost/.注销时也会发生同样的情况,即尝试打开网址http://localhost/logout/而不是http://localhost/.基本上,当页面打开时http://localhost/login,redirect('/')将/添加到当前网址的末尾,并且瞧 - 我得到了一个我没想到的网址 - http://localhost/login/.我无法使用重定向将其重定向到站点的根目录.
请帮助我解决这个问题,如果可能的话还要解释Django这种不合理行为的原因
我正在使用 Django 3.1。这就是我为实现这一目标所做的:
在 urls.py
from django.shortcuts import redirect
urlpatterns = [
path('', lambda req: redirect('/myapp/')),
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls'))
]
Run Code Online (Sandbox Code Playgroud)
如果您查看重定向文档,则可以将以下内容传递给该函数:
通常,我认为重定向到视图名称而不是URL更好。在您的情况下,假设您的urls.py具有类似于以下内容的条目:
url(r'^$', 'Home.views.index'),
Run Code Online (Sandbox Code Playgroud)
我会改用这样的重定向:
redirect('Home.views.index')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13857 次 |
| 最近记录: |