如何使用 reverse() 将 Django 请求中的 Referer URL 与另一个 URL 进行比较?

How to compare Referer URL in Django Request to another URL using reverse()?

我如何比较引用者 URL 和 reverse() url?

这是我当前的代码:

if request.META.get('HTTP_REFERER') == reverse('dashboard'):
    print 'Yeah!'

但这行不通,因为反向会输出/dashboard,而HTTP_REFERER会输出http://localhost:8000/dashboard/

我目前的解决方案是:

if reverse('dashboard') in request.META.get('HTTP_REFERER'):
    print 'Yeah!'

我不知道这是否是最好的方法。任何建议都会很棒。

您可以使用 urlparse 从 URL 获取路径元素。在 Python3:

from urllib import parse
path = parse.urlparse('http://localhost:8000/dashboard/').path

并在 Python 2:

import urlparse
path = urlparse.urlparse('http://localhost:8000/dashboard/').path