【问题标题】:Django redirect to root from a viewDjango 从视图重定向到根目录
【发布时间】: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


【解决方案1】:

还补充了 Ken Cloud 的答案,如果您已命名 url,则只需调用 url 名称:

from django.shortcuts import redirect

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这很好用,但你能解释一下它是如何工作的吗?具体来说,如果我只使用重定向而不使用 lambda,为什么它不起作用谢谢。
    【解决方案3】:

    如果您查看documentation for redirect,您可以将几件事传递给函数:

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

    一般来说,我认为重定向到视图名称而不是 URL 会更好。在你的情况下,假设你的 urls.py 有一个看起来像这样的条目:

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

    我会改用这样的重定向:

    redirect('Home.views.index')
    

    【讨论】:

    • jterrace 是对的,因为您使用的是url(),您可以nameurl(r'^$','Home.views.index',name="home_index") 并在视图中使用它作为return HttpResponseRedirect(reverse('home_index')) 也可以在模板中使用它与&lt;a href={% url home_index %}&gt;home&lt;/a&gt;
    猜你喜欢
    • 1970-01-01
    • 2015-09-02
    • 2019-07-20
    • 2021-11-26
    • 2015-04-23
    • 2012-03-07
    • 2015-10-21
    • 2012-08-15
    • 2014-10-22
    相关资源
    最近更新 更多