从另一个应用程序的视图重定向到根URL

时间:2019-06-14 19:34:54

标签: django

当我在不登录用户的情况下访问应用程序的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_urlredirect(redirect_URL)中的添加,这意味着我无法再访问localhost:8000

最后的笔记:

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

  

/ professors /

处的NoReverseMatch      

找不到与“”相反的字符。 ''不是有效的视图函数或模式名称。   这表明起点再次来自localhost:800/professors/

1 个答案:

答案 0 :(得分:0)

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='/'
相关问题