【发布时间】:2019-05-21 07:23:03
【问题描述】:
我对位于 python 文件中的函数中的请求属性有一点疑问(不是我的观点):
def my_function(model, request):
instance = model.objects.filter(application=request.cur_app, display=True).order_by('order')
return instance
在同一个文件中,我这样调用我的函数:
for element in my_function(my_model):
... do something ...
但我遇到了这个问题:
my_function() missing 1 required positional argument: 'request'
我不明白如何解决这个问题,因为如果我在循环中添加“请求”,我会得到:
name 'request' is not defined
谢谢!
更新:
我有一个 middleware.py 文件,其中包含:
class MultiSiteMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.cur_app = WebApplication.objects.get_current(request)
return self.get_response(request)
这是我想在这个函数的 menu.py 文件中获取的中间件:
def list_of_edition():
""" Return list of editions
:return queryset
"""
instance = NavbarMenuSettings.objects.filter(application=MultiSiteMiddleware, display=True).order_by('order')
return instance
【问题讨论】:
-
根据函数定义
def my_function(model, request):,请求参数是必需的。在此函数调用的其他地方,请求参数如何传递到my_function? -
@Praveenkumar 我尝试在调用此函数时添加
request(仅在我的代码中一次),但是通过这种方式,未定义请求。调用我的函数的唯一地方对应于我的 for-loop 示例 -
request对象由 Django 自动注入到您的视图中。如果你真的需要其他python文件或函数中的请求对象,那么最简单的方法就是将请求对象从view传递到其他地方。 -
@Praveenkumar 有什么例子可以分享一下,看看我到底要写什么?
-
您不能全局访问请求对象,也不能在不将请求作为参数的其他函数中访问。您只能在将其作为参数接收的函数中访问它。您能否详细说明您在全球范围内访问它的确切需求?