English 中文(简体)
利用Django的环境处理器获取全球变量
原标题:Accessing global variable in view using context processor in Django

假设我有一个背景程序:

def title(request):
   return { titles :  mytitle }

我可在以下模板中查阅这一变量:{<>>>%>>。

但是,我如何能够这样做?

def myview(request):
    print request.titles

页: 1 WSGIRequest审校没有资格证书


或者,(比情况处理器)采取更好的办法,使全球变量在观点和模板中都能获得?

提前感谢。

最佳回答

背景处理器以任何方式是全球变量。 这些只是请求书全文启动时的职能,因而增加了这方面的内容。 因此,只有在你有请求书全文时,他们才可以重新获得。

你的事例并没有真正给人一个好的想法,即你想获得哪些变量。 如果你只想在任何地方使用一些固定装置,那么,一种很好的方法就是在什么地方界定这些单元,在环境中就这样说,在你们需要的地方进口这一模块,同时利用背景处理器添加这些内容。

问题回答

Add your context processor method path (folder.context_processor.application_context) to TEMPLATE_CONTEXT_PROCESSORS.

in my case application_context is the method which i defined inside file context_processor.py and method "application_context" returns { titles : mytitle }

如果你们想将“标题”作为全球观点变量加以使用,则以这种方式使用。

global_var = RequestContext(request).get("app_config")
titles = global_var.get("titles")
print titles 

The only advantage is "Same variable titles will be visible for templates and also in your views"

如果你需要你的意见中的数据,那么与背景进程者一道使用中世纪知识会更清洁:

  1. Create a trivial custom middleware to store some data on the request object, say at request.x (example). Now you can access this in your views directly.
  2. Enable django.core.context_processors.request in your TEMPLATE_CONTEXT_PROCESSORS to have request.x accessible from your templates.

见我的相关问题:。 Django: 如何为所有观点(而不是模板)提供背景?





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签