在中间件中设置要在模板中访问的变量 [英] Setting a variable in middleware to be accessed in the template
问题描述
我似乎很难在我可以在模板层中访问的一个中间件类中设置变量。
I seem to be having difficulty setting a variable in one of my middleware classes that I can then access in the template layer.
基本布局是这样的:
class TheMiddleware(object):
def __init__(self, etc):
stuff...
def process_response(self, request, response):
request.my_var = "whatever"
return response
然后在模板上查看其他视图:
Then on the template for a different view I have:
{% custom_tag arg_a %}
这是一个模板标签,应从请求中返回变量:
Which is is a template tag that should return the variable from the request:
@register.simple_tag
def custom_tag(arg_a):
return threading.currentThread().request.my_var
此错误以呈现时捕获的AttributeError出现:'WSGIRequest'对象没有属性' my_var'
我认为这可能是我在模版标签中访问请求的方式。因此,我在此问题中添加了django.core.context_processors.request到我的TEMPLATE_CONTEXT_PROCESSORS中。 / a>并尝试将请求对象传递给标记,然后直接从模板访问请求,但是没有运气。
I thought it might be the way I was accessing the request in the template tag. So I added django.core.context_processors.request to my TEMPLATE_CONTEXT_PROCESSORS as in This question and tried passing the request object to the tag, then accessing request directly from the template but with no luck.
我想我对请求对象的方式缺乏了解工作。是否可以将变量分配给请求对象并在多个视图上选取该变量?我以为请求对象是通过视图传递的,但似乎却生成了一个新实例。
I think I lack an understanding on how request objects work. Is it possible to assign a variable to a request object and pick that variable up several views on? I thought the request object was passed through the views, but it seems that instead a new instance is generated.
如果是这种情况,您将如何在中间件中存储全局变量,然后可以从应用程序的任何位置访问它,无论是在视图中还是在视图中模板?
If that is the case, how would you go about storing a global variable within middleware that you could then access from any point in your app, be it in a view or a template?
更新:
要消除混乱(是否属于我或其他不确定的事物!)我不试图在视图的process_response中间件中设置请求变量,然后在同一视图的模板中将其提取。据我了解,这是行不通的,因为在保存变量之前已对模板进行了处理。 (这是我的故意行为。)
To clear up the confusion (whether mine or others I'm not sure!) I'm not trying to set the request variable in the process_response middleware of a view and then pick it up in the template of that same view. I understand that that wouldn't work because the template has been processed before the variable is saved. (This is a deliberate act on my part).
我有两个视图,分别是 view1 和 view2 有一个装饰器,该装饰器使中间件在请求中设置变量。希望在设置变量之后使用view2模板。
I have two views, view1 and view2 view one has a decorator that causes the middleware to set the variable in the request. It is the view2 template, which comes after the variable has been set, that I wish to access the variable.
推荐答案
您尝试
我认为您应该实现 process_request()
而不是设置变量。
I think you should be implementing process_request()
instead to set the variable.
def process_request(self, request):
request.my_var = "whatever"
return
这篇关于在中间件中设置要在模板中访问的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!