简要步骤:

1.编辑一个函数:

def media_url(request):
from django.conf import settings
return {'media_url': settings.MEDIA_URL}

2.配置settings:

TEMPLATE_CONTEXT_PROCESSORS = ('myapp.context_processors.media_url',)

3.确保几点:

1)使用RequestContext

return render_to_response("my_app/my_template.html", {'some_var': 'foo'},
context_instance=RequestContext(request))

2)确定函数media_url所在的app包含在INSTALLED_APPS中。

Last time around we looked at how to write an effective template tag, with the focus on writing a flexible template tag that would make it easy to pull in various types of recent content in any page; I use a tag similar to the one in that entry to pull out the recent entries, links
and comments in the footer of every page on this site.

For situations where you want to get content out of your database, a template tag is typically the best way to go, but consider a related situation: what happens when you want a particular variable — not a content object — to be available in the context
of every template?

You could write a template tag to populate that variable, and it’d be extremely easy to do with a convenience function Django provides: the
simple_tag decorator, which lets you omit a lot of the boilerplate of writing a template tag when all you want is to spit out some value into the template.

A recent example that came up on the django-users mailing list was a template tag to retrieve the base
URL for your media (typically you want to store “media” like images, stylesheets and JavaScript in a particular location on your server, or possibly even have a separate server for
them if you’re using Apache and mod_python — incurring the overhead of mod_python on a request which will just serve up a file from disk wastes resources). Django lets you specify where your media files come from via the
MEDIA_URL setting.

So you’d write a simple tag which imports your settings file and returns the value of the
MEDIA_URL setting into the template context; you could maybe call it
get_media_url. But having to call that in every single template will probably get a bit cumbersome and feels like it violates the
DRY principle; wouldn’t it be nice if Django provided an easier way to do this?

Enter RequestContext and context processors

As it turns out, Django provides an extremely easy way to do this. Every time you render a template, you give it a “context”; this is a dictionary-like object whose keys are variable names and whose values are the values of the variables. When you render
a template with a given context, every key in the context dictionary becomes a variable in the template that you can access and use.

The base class for Django template contexts is django.template.Context, and typically you use it somewhat like this:

from django.template import Context
# view code here...
c = Context({'some_var': 'some_value', 'some_other_var': 'some_other_value'})

But because Context is a Python class, you can subclass it and do all sorts of nifty tricks with it. And Django provides a particularly useful pre-defined
Context subclass: django.template.RequestContext. Old hands will recognize this as a variation of
DjangoContext, a Context subclass present in older releases of Django which would automatically add useful variables like the logged-in user who requested the page. But
RequestContext is DjangoContext on steroids.

RequestContext looks in your settings file for a setting called TEMPLATE_CONTEXT_PROCESSORS, which should be a tuple of callable objects, each of which should return a dictionary;
RequestContext will loop over each one of them, call it, and add the key/value pairs from its returned dictionary to the template context as variables. Django includes a few built-in context processors (found in
django.core.context_processors) which can add:

  • The user who requested the page (django.core.context_processors.auth)
  • A test for the DEBUG setting and a list of
    SQL
    executed in the request (django.core.context_processors.debug)
  • Information about the language settings used for any translations performed by the internationalization system (django.core.context_processors.i18n)
  • The full HttpRequest object for the current request (django.core.context_processors.request)

Using RequestContext and a context processor automatically adds these variables in every template, which avoids the repetitiveness of having to call a template tag in each template just to add some variables.

Let’s write a context processor

And, even better, it’s absurdly simple. Let’s use the example above — getting the
MEDIA_URL setting — and see how we can add it the context of our templates by using
RequestContext.

First we write the context processor. It’s an extremely simple function:

def media_url(request):
from django.conf import settings
return {'media_url': settings.MEDIA_URL}

Notice that it takes the current request’s HttpRequest instance as an argument; in this example we’re not using that, but if you want to return different things based on attributes of the request it’ll be there for you.

This function can live anywhere in your application’s code, but for sake of consistency and being able to remember where it is, I’d recommend creating a new file in your application’s directory called “context_processors.py” and putting the function there.

Then we open up our settings file and add this (keep in mind that Django enables the
auth, debug and i18n context processors by default, and editing the
TEMPLATE_CONTEXT_PROCESSORS setting will override that, so if you want to keep those you’ll need to add them back manually):

TEMPLATE_CONTEXT_PROCESSORS = ('myapp.context_processors.media_url',)

Note the trailing comma there; even if you’re only putting one item into a Python tuple it still needs a comma.

Finally, we change our view code to use RequestContext instead of the base
Context class. In most cases, this is as simple as changing one line at the top of the view file; instead of

from django.template import Context

we do this:

from django.template import RequestContext

Now when we instantiate a context, we can do it by RequestContext(request, context_dictionary) instead of
Context(context_dictionary).

If you’re using the render_to_response shortcut, just pass it as the
context_instance keyword argument to render_to_response, like so:

return render_to_response("my_app/my_template.html", {'some_var': 'foo'},
context_instance=RequestContext(request))

If you’re using a generic view, you don’t have to do anything except define the TEMPLATE_CONTEXT_PROCESSORS setting; generic views use
RequestContext by default.

And you’re done; now you’ll get your media_url variable available in all of your templates without having to repetitively call a template tag.

自定义django的Template context processors的更多相关文章

  1. Django.template框架 template context (非常详细)

    前面的章节我们看到如何在视图中返回HTML,但是HTML是硬编码在Python代码中的 这会导致几个问题: 1,显然,任何页面的改动会牵扯到Python代码的改动 网站的设计改动会比Python代码改 ...

  2. Django之Template

    模板层(template) 概念:  模板与html的区别:  模板=html+模板语法 模板语法: 1 变量:       {{}}    深度查询: 通过句点符.    列表,字典    clas ...

  3. django模板(template)

    模板层(template) 你可能已经注意到我们在例子视图中返回文本的方式有点特别. 也就是说,HTML被直接硬编码在 Python代码之中. 1 2 3 4 def current_datetime ...

  4. 六、Django之Template

    一.Template由来 1.任何前端页面的改动都和后端有关: 2.前端HTML和后端python分开能让网站更加清晰: 3.前后端分离的趋势下,专业的事交给专业的人做. 二.Django中的temp ...

  5. Django之template操作

    一.模板渲染的原理 (一)使用 模板渲染首先有一个模板对象Template,然后有一个上下文对象Context,通过render方法进行渲染,最后返回字符串,render方法的本质还是调用了HttpR ...

  6. 自定义django admin及其界面

    1.在项目目录下新创建一个app,命名为kingadmin,在templates目录下新建kingadmin目录,用来存放相关页面的模板文件,新建一个templatetags目录,用来存放处理前端模板 ...

  7. Django——模版Template报错

    >>> from django.template import Template >>> t = Template("My name is {{ my_n ...

  8. 自定义Django认证系统的技术方案

    Django已经提供了开箱即用的认证系统,但是可能并不满足我们的个性化需求.自定义认证系统需要知道哪些地方可以扩展,哪些地方可以替换.本文就来介绍自定义Django认证系统的相关技术细节. 自定义认证 ...

  9. SharePoint 2013 Step by Step——使用自定义的List Template

    Overview 对于企业员工来说,"扁平结构"的LIST是日常操作中经常使用到的,LIST的好处是方便数据的录入以及数据的整理分析,尤其是Quick Edit功能,可以实现快速编 ...

随机推荐

  1. android指纹识别、拼图游戏、仿MIUI长截屏、bilibili最美创意等源码

    Android精选源码 一个动画效果的播放控件,播放,暂停,停止之间的动画 用 RxJava 实现 Android 指纹识别代码 Android仿滴滴打车(滴滴UI)源码 Android高仿哔哩哔哩动 ...

  2. 复习java第五天(枚举、Annotation(注释) 概述)

    一.枚举 传统的方式: •在某些情况下,一个类的对象是有限而且固定的.例如季节类,只能有 4 个对象 •手动实现枚举类: —private 修饰构造器. —属性使用 private final 修饰. ...

  3. ASP.NET Cache 实现依赖Oracle的缓存策略

    ASP.NET 中的缓存提供了对SQL依赖项的支持,也就是说当SQL SERVER数据库中的表或行中的数据被更改后,缓存中的页面就失效,否则,页面输出可一直保留在缓存当中.这确实为程序员提供了方便.但 ...

  4. GrepWin:Win7下的文本替换工具

    工作环境退回到Win7之后,内容查找功能非常不给力,推荐一个文本内容查找工具grepWin. Win7下的文本查找/替换工具: grepWin

  5. python tips:类的绑定方法(bound)和非绑定方法(unbound)

    类属性只有类及其实例能够访问,可以理解为一个独立的命名空间. Python中类属性的引用方式有两种: 1. 通过类的实例进行属性引用,称为绑定方法(bound method),可以理解为方法与实例绑定 ...

  6. Android 性能测试初探(二)

    书接前文 Android 性能测试初探(一).上回大体介绍了下在 android 端的性能测试项,现在我们就细节测试项做一些阐述(包括如何自己 DIY 测试). 首先我们来说说启动时间.关于应用的启动 ...

  7. eas之MrpUI

    package com.kingdee.eas.custom.mrp.client; import java.awt.Component;import java.awt.event.*;import ...

  8. 【剑指Offer】59、按之字形顺序打印二叉树

      题目描述:   请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推.   解题思路:   这道题仍然是二 ...

  9. VirtualBox安装增强包实现文件共享

    环境: win10 64位 Virtualbox 5.1.30 ubuntu-16.04.3-server-amd64.iso 1. 安装好ubuntu后,打开virtualbox安装路径文件夹,找到 ...

  10. python 实现kmeans聚类

    编程中在做数值相等判断的时候,直接使用==判断并不可靠.实际上经过运算后的两个值(浮点型)并不可能完全一致,可能会因为小数点后的些许差异导致判断为false. 比如: 1 print 1e-5 == ...