ali*_*s51 9 django django-urls django-views
我目前正在使用以下函数来获取参考视图:
def get_referer_view(request, default=None):
referer = request.META.get('HTTP_REFERER')
if not referer:
return default
# remove the protocol and split the url at the slashes
referer = re.sub('^https?:\/\/', '', referer).split('/')
if referer[0] != request.META.get('SERVER_NAME'):
return default
# add the slash at the relative path's view and finished
referer = u'/' + u'/'.join(referer[1:])
return referer
Run Code Online (Sandbox Code Playgroud)
如果我view由于编程逻辑而重定向,例如..
return HttpResponseRedirect('dashboard')
Run Code Online (Sandbox Code Playgroud)
...有没有一种方法可以在不使用的情况下获取引用视图,HTTP_REFERER以便我可以在重定向中使用该变量view?这并不总是在浏览器的标头中设置。
请注意,因为视图是按语法重定向的,所以我无法使用 POST 来收集数据。
也许可以以某种方式设置和检索自定义标头?
对于那些感兴趣的人,这是我得出的解决方案。技巧是在第一个请求之后设置一个 cookie 来存储view_name或,然后在渲染视图之前path调用它并保存到。request
class MyMiddleware:
def __init__(self, get_response):
# One-time configuration and initialization.
self.get_response = get_response
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
# Add the referer cookie be accessible in request.response
request.referer_view = request.COOKIES.get('referer_view', None)
request.referer_path = request.COOKIES.get('referer_path', None)
print('request.referer_view', request.referer_view)
print('request.referer_path', request.referer_path)
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
# Set a cookie with the current view name that is cleared each time the view changes
response.set_cookie('referer_view', request.resolver_match.view_name)
response.set_cookie('referer_path', request.path)
return response
Run Code Online (Sandbox Code Playgroud)
每次视图更改时,这些值都会在此循环中更新。
| 归档时间: |
|
| 查看次数: |
640 次 |
| 最近记录: |