【问题标题】:Redirecting to root URL from another app's view从另一个应用程序的视图重定向到根 URL
【发布时间】:2019-06-14 19:34:54
【问题描述】:

当用户在未登录的情况下访问应用程序的 URL 时,我试图重定向到根 URL。

我尝试了两种方法:

  1. 使用装饰器
@login_required(login_url = '')
def index(request):
    return render(request, 'professors/index.html')

返回 404 错误,说明当前路径为 accounts/login

  1. 将根页面的views 传递给redirect
def index(request):
    if request.user.is_authenticated:
        return render(request, 'professors/index.html')
    else:
        return redirect('login.views.index')

返回 404 错误,说明当前路径为 professors/login.views.index

根 URL 是 localhost:8000/,当用户未登录时,我在访问 localhost:8000/professors/ 后尝试重定向到它。

这个问题与我在这里发现的类似:Django redirect to root from a view

但是,应用该解决方案对我不起作用。看起来当从应用程序的视图重定向到根目录时,它重定向到的根目录是应用程序的根目录,而不是网站的根目录,这对于访问应用程序 URL 后重定向的任何 URL 都是如此。例如,如果根 URL 是 localhost:8000 而应用程序的 URL 是 localhost:8000/professors/,那么尝试从后者访问任何其他 URL,将意味着 localhost:8000/professors/ 是起点,我在 login_url 中写的内容或redirect(redirect_URL) 被添加到那,这意味着我不能再访问localhost:8000

最后说明:

当我在else 中尝试return redirect ('') 时,它返回了

NoReverseMatch 在 /professors/

找不到''的反向。 '' 不是有效的视图函数或模式名称。 这说明起点又是从localhost:800/professors/

【问题讨论】:

    标签: django


    【解决方案1】:

    login_required decorator中设置你的login_url参数,

    @login_required(login_url='/')
    def index(request):
        return render(request, 'professors/index.html')

    您也可以在settings

    中设置LOGIN_URL
    #settings.py
    LOGIN_URL='/'
    

    【讨论】:

    • 谢谢!它确实重定向到主页,但显示的 URL 是 http://localhost:8000/?next=/professors/ 而不是 http://localhost:8000,知道为什么吗?另外,为什么重定向不起作用?
    • 这是redirect_field_name。当您从根 url 进行身份验证时,Django 会将您带到 /professors/,这是您首先尝试访问的 URL。
    • 愿意,但必须等几分钟才可以。那么,我必须使用装饰器进行重定向吗?换句话说,如果没有装饰器,我不能在 URL 中“返回”?
    • ^(我想你在我能够编辑之前查看了评论)
    • 是的..你是对的。没有该装饰器,您将无法返回 URL。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多