-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
django-global-template-variable-by-use-custom-context-processor.html
296 lines (253 loc) · 18.5 KB
/
django-global-template-variable-by-use-custom-context-processor.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
<!DOCTYPE html>
<html lang="zh-hans" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml" class="han-init">
<head>
<title>[django]使用自定义 context processor 实现模板全局变量 - Mozillazg's Blog</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://mozillazg.com/favicon.ico" rel="icon">
<link rel="canonical" href="https://mozillazg.com/2013/01/django-global-template-variable-by-use-custom-context-processor.html">
<meta name="author" content="mozillazg" />
<meta name="keywords" content="python,django" />
<meta name="description" content="本文使用的是 django 1.4.3。 写一个 context processor 函数 可以把这个函数放在项目的任何地方,本文是放在应用目录下的 context_processors.py 文件中: from hello.models import Category def categories(request): # 只有一个参数(HttpRequeset 对象) all_categories = Category.objects.all() context = {'categories': all_categories} return context # 返回值必须是个字典 注意:context processor 函数只有一个参数,即 HttpRequest 对象,并且函数的返回值必须是个字典。 修改 settings 文件 修改 TEMPLATE_CONTEXT_PROCESSORS 选项值,添加新建的 ..." />
<meta property="og:site_name" content="Mozillazg's Blog" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="[django]使用自定义 context processor 实现模板全局变量"/>
<meta property="og:url" content="https://mozillazg.com/2013/01/django-global-template-variable-by-use-custom-context-processor.html"/>
<meta property="og:description" content="本文使用的是 django 1.4.3。 写一个 context processor 函数 可以把这个函数放在项目的任何地方,本文是放在应用目录下的 context_processors.py 文件中: from hello.models import Category def categories(request): # 只有一个参数(HttpRequeset 对象) all_categories = Category.objects.all() context = {'categories': all_categories} return context # 返回值必须是个字典 注意:context processor 函数只有一个参数,即 HttpRequest 对象,并且函数的返回值必须是个字典。 修改 settings 文件 修改 TEMPLATE_CONTEXT_PROCESSORS 选项值,添加新建的 ..."/>
<meta property="article:published_time" content="2013-01-23" />
<meta property="article:section" content="django" />
<meta property="article:tag" content="python" />
<meta property="article:tag" content="django" />
<meta property="article:author" content="mozillazg" />
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@mozillazg">
<meta name="twitter:creator" content="@mozillazg">
<meta name="twitter:domain" content="https://mozillazg.com">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://mozillazg.com/theme/css/bootstrap.min.css" type="text/css"/>
<link href="https://mozillazg.com/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="https://mozillazg.com/theme/css/pygments/github.css" rel="stylesheet">
<link rel="stylesheet" href="https://mozillazg.com/theme/css/style.css" type="text/css"/>
<link href="https://mozillazg.com/static/custom.css" rel="stylesheet">
<link href="https://mozillazg.com/feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="Mozillazg's Blog ATOM Feed"/>
<link href="https://mozillazg.com/feeds/all.rss.xml" type="application/rss+xml" rel="alternate"
title="Mozillazg's Blog RSS Feed"/>
<link href="https://mozillazg.com/feeds/django.atom.xml" type="application/atom+xml" rel="alternate"
title="Mozillazg's Blog django ATOM Feed"/>
</head>
<body>
<div class="navbar" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="https://mozillazg.com/" class="navbar-brand">
Mozillazg's Blog </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/index.html">Home</a></li>
<li><a href="https://mozillazg.com/feeds/all.atom.xml">Feed</a></li>
<li><a href="https://mozillazg.com/2014/10/pages/about-me.html">
About me
</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="https://mozillazg.com/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-lg-12">
<section id="content" class="yue">
<article>
<header class="text-center">
<h1>
<a href="https://mozillazg.com/2013/01/django-global-template-variable-by-use-custom-context-processor.html"
rel="bookmark"
title="Permalink to [django]使用自定义 context processor 实现模板全局变量">
[django]使用自定义 context processor 实现模板全局变量
</a>
</h1>
<p class="published">
<time datetime="2013-01-23T00:00:00+00:00">
2013-01-23
</time>
</p>
</header>
<div class="entry-content">
<div class="well-sm article-info">
<footer class="post-info">
<a href="https://mozillazg.com/category/django.html">django</a>
<span class="label label-default hide">Tags</span>
<a href="https://mozillazg.com/tag/python.html">python</a>
/
<a href="https://mozillazg.com/tag/django.html">django</a>
</footer><!-- /.post-info --> </div>
<div>
<p>本文使用的是 django 1.4.3。</p>
<h2 id="context-processor">写一个 context processor 函数</h2>
<p>可以把这个函数放在项目的任何地方,本文是放在应用目录下的 context_processors.py 文件中:</p>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">hello.models</span> <span class="kn">import</span> <span class="n">Category</span>
<span class="k">def</span> <span class="nf">categories</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="c"># 只有一个参数(HttpRequeset 对象)</span>
<span class="n">all_categories</span> <span class="o">=</span> <span class="n">Category</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="n">context</span> <span class="o">=</span> <span class="p">{</span><span class="s">'categories'</span><span class="p">:</span> <span class="n">all_categories</span><span class="p">}</span>
<span class="k">return</span> <span class="n">context</span> <span class="c"># 返回值必须是个字典</span>
</pre></div>
<p>注意:context processor 函数只有一个参数,即 HttpRequest 对象,并且函数的返回值必须是个字典。</p>
<h2 id="settings">修改 settings 文件</h2>
<p>修改 TEMPLATE_CONTEXT_PROCESSORS 选项值,添加新建的 context processor 函数。
如果没有 TEMPLATE_CONTEXT_PROCESSORS 这一项的话,需要把它添加到 settings 文件中。
各版本的 django 的 TEMPLATE_CONTEXT_PROCESSORS 的默认值不一样,具体见 <a href="https://docs.djangoproject.com/en/1.4/ref/settings/#template-context-processors">TEMPLATE_CONTEXT_PROCESSORS</a>。</p>
<div class="codehilite"><pre><span class="n">TEMPLATE_CONTEXT_PROCESSORS</span> <span class="o">=</span> <span class="p">(</span>
<span class="s">'django.contrib.auth.context_processors.auth'</span><span class="p">,</span>
<span class="s">'django.core.context_processors.debug'</span><span class="p">,</span>
<span class="s">'django.core.context_processors.i18n'</span><span class="p">,</span>
<span class="s">'django.core.context_processors.media'</span><span class="p">,</span>
<span class="s">'django.core.context_processors.static'</span><span class="p">,</span>
<span class="s">'django.core.context_processors.tz'</span><span class="p">,</span>
<span class="s">'django.contrib.messages.context_processors.messages'</span><span class="p">,</span>
<span class="s">'hello.context_processors.categories'</span><span class="p">,</span> <span class="c"># 自定义的 context processors 函数</span>
<span class="p">)</span>
</pre></div>
<h2 id="views">在 views 中使用</h2>
<div class="codehilite"><pre><span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">RequestContext</span>
<span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">loader</span>
<span class="c"># 第一种用法</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s">'index.html'</span><span class="p">,</span> <span class="p">{</span><span class="s">'foo'</span><span class="p">:</span> <span class="s">'bar'</span><span class="p">},</span>
<span class="n">context_instance</span><span class="o">=</span><span class="n">RequestContext</span><span class="p">(</span><span class="n">request</span><span class="p">))</span>
<span class="c"># 第二种用法</span>
<span class="k">def</span> <span class="nf">hello</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s">'index.html'</span><span class="p">)</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">RequestContext</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="p">{</span><span class="s">'foo'</span><span class="p">:</span> <span class="s">'bar'</span><span class="p">})</span>
<span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">))</span>
</pre></div>
<h2 id="_1">模板中使用定义的变量</h2>
<div class="codehilite"><pre>Categories:
<span class="nt"><ul></span>
<span class="c">{# 自定义的 context processor 函数的返回值是:{'categories': all_categories},该字典的 key 可以直接在模板中作为变量使用 #}</span>
<span class="cp">{%</span> <span class="k">for</span> <span class="nv">category</span> <span class="k">in</span> <span class="nv">categories</span> <span class="cp">%}</span>
<span class="nt"><li></span><span class="cp">{{</span> <span class="nv">category.title</span> <span class="cp">}}</span><span class="nt"></li></span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
<span class="nt"></ul></span>
</pre></div>
<p>结果:</p>
<blockquote>
<p>Categories:</p>
<ul>
<li>python</li>
<li>django</li>
</ul>
</blockquote>
<p>示例项目下载:<a href="/static/downloads/2013.01.23.mysite.tar.gz">mysite.tar.gz</a>,django 版本:1.4.3。</p>
<h2 id="_2">参考</h2>
<ul>
<li><a href="http://matthewphiong.com/django-global-template-variable">Django “Global” Template Variable — matthewphiong blog</a></li>
<li><a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.RequestContext">django.template.RequestContext</a></li>
<li><a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors">Writing your own context processors</a></li>
<li><a href="https://docs.djangoproject.com/en/1.4/ref/settings/#template-context-processors">TEMPLATE_CONTEXT_PROCESSORS</a></li>
<li><a href="https://docs.djangoproject.com/en/dev/faq/usage/#how-do-i-make-a-variable-available-to-all-my-templates">How do I make a variable available to all my templates?</a></li>
</ul>
</div>
</div>
<!-- /.entry-content -->
<section class="well" id="related-posts">
<p>Related Posts:</p>
<ul>
<li><a href="https://mozillazg.com/2013/06/django-south-rename-model-or-table.html">[django]使用 South 重命名 model 名称</a></li>
<li><a href="https://mozillazg.com/2013/02/django-typeerror-decod-argument-1-must-be-string-not-none.html">[django] 创建后台超级用户时出现 TypeError: decode() argument 1 must be string, not None 错误</a></li>
<li><a href="https://mozillazg.com/2013/10/django-TypeError-delete-got-an-unexpected-keyword-argument-using.html">[django]修复 "TypeError: delete() got an unexpected keyword argument 'using'"</a></li>
<li><a href="https://mozillazg.com/2013/04/django-custom-model-display-name-on-admin-pages.html">[django]自定义 model 在后台显示的名称</a></li>
<li><a href="https://mozillazg.com/2014/03/django-save-uploaded-file-with-utf8-encoding-by-custom-model-field.html">[django]通过自定义 Model Field 的方式将上传的文本文件按 UTF-8 编码保存</a></li>
</ul>
</section>
<hr/>
<section class="comments" id="comments">
<h2>Comments</h2>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'my-github-blog'; // required: replace example with your forum shortname
var disqus_identifier = 'django-global-template-variable-by-use-custom-context-processor';
var disqus_url = 'https://mozillazg.com/2013/01/django-global-template-variable-by-use-custom-context-processor.html';
var disqus_config = function () {
this.language = "zh-hans";
};
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by
Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</section>
</article>
</section>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2016 mozillazg
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> <p><small> <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="/static/images/by-sa-80x15.png" /></a>
"<span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Mozillazg's Blog</span>" by <a xmlns:cc="http://creativecommons.org/ns#" href="https://mozillazg.com" property="cc:attributionName" rel="cc:attributionURL">mozillazg</a> is
licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>, except where indicated otherwise.
</small></p>
</div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="https://mozillazg.com/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://mozillazg.com/theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="https://mozillazg.com/theme/js/respond.min.js"></script>
<!-- Disqus -->
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'my-github-blog'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<!-- End Disqus Code -->
<!-- Google Analytics Universal -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-77172981-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics Universal Code -->
</body>
</html>