Django 从视图重定向到根目录

17 投票
3 回答
29321 浏览
提问于 2025-04-17 01:15

我正在创建一个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('/')

现在,当我访问登录页面时,一切正常。但是在我提交表单后,出现了一个错误,提示找不到模块urls。经过一番查找,我发现redirect("/")实际上变成了http://localhost/login/,而不是http://localhost/。注销时也是这样,也就是说,它试图打开http://localhost/logout/,而不是http://localhost/。简单来说,当页面打开的是http://localhost/login时,redirect('/')会在当前网址的末尾加上一个斜杠,这样我就得到了一个意想不到的网址http://localhost/login/。我无法通过这个重定向让它回到网站的根目录。

请帮我解决这个问题,如果可以的话,也请解释一下Django这种不合理行为的原因。

3 个回答

1

另外,补充一下Ken Cloud的回答,如果你有命名的链接,你可以直接调用这个链接的名字:

from django.shortcuts import redirect

urlpatterns = [
    path('app/', include('myapp.urls'), name='app')
    path('', lambda req: redirect('app')),
    path('admin/', admin.site.urls),
]
5

如果你查看一下重定向的文档,你会发现可以传递给这个函数的东西有好几种:

  • 一个模型
  • 一个视图名称
  • 一个网址

一般来说,我觉得重定向到视图名称比直接重定向到网址更好。在你的情况下,假设你的urls.py文件里有一条看起来像这样的记录:

url(r'^$', 'Home.views.index'),

我会这样使用重定向:

redirect('Home.views.index')
15

我正在使用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'))
]

撰写回答