Django:有没有办法知道一个url在应用程序中是否有效?

Django:有没有办法知道一个url在应用程序中是否有效?

问题描述:

这是我的目标:


  • 用户想登录

  • 我打开一个按钮每个页面以urlback为参数,例如,如果我们在页面上 http://olivier.life/today ,则登录的按钮将具有像 http://olivier.life/login?back=today

  • 用户登录

  • 一旦用户登录,我检查 GET 请求中是否有返回。如果是这样,那么我将重定向到 GET

  • the user wants to login
  • I make a button on each page with the urlback as a parameter, for example if we are on the page http://olivier.life/today, the button to login will have an url like http://olivier.life/login?back=today
  • the user logs in
  • once the user is logged in, i check if there's a "back" in the "GET" request. if so then I make a redirect to the url in the GET

我的url问题是一个安全问题:我只想知道 GET 中的URL是否是我的应用程序的一部分(对 urls.py 文件)。

My problem is a security problem: I just want to know if the URL in the GET is part of my application (is valid for one of the URLs in the urls.py file).

如何做?

使用 resolve 。有一个例子与文档中的这个用例非常接近。我想你的情况你想要的是:

Use resolve. There's an example that's very close to this use case in the docs. I think for your case you want something like:

def some_view(request):
    redirect_target = request.GET.get('back')
    if redirect_target:
        try:
            resolve_match = django.core.urlresolvers.resolve(redirect_target)
        except django.core.urlresolvers.Resolver404:
            # do something on bad input
        else:
            return django.shortcuts.redirect(redirect_target)
    else:
        # empty string redirect target, or not provided at all
        # do something else