自定義django的Template context processors

簡要步驟:

1.編輯一個函數:

def media_url(request):from django.conf import settingsreturn {'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 settingsreturn {'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.

轉載于:https://www.cnblogs.com/chenjianhong/p/4144737.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:
http://www.pswp.cn/news/377995.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377995.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377995.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

十四、Canny邊緣提取

一、算法步驟 1,對圖像進行GaussianBlur(高斯模糊)消除一些噪聲 2,對圖像進行灰度轉換cvtColor 3,計算梯度Sobel/Scharr 4,非最大信號抑制 5,高低閾值輸出二值圖像 設定兩個閾值T1和T2,凡是高于T2的都保…

scanner close_Java Scanner close()方法與示例

scanner close掃描器類close()方法 (Scanner Class close() method) close() method is available in java.util package. close()方法在java.util包中可用。 close() method is used to close this Scanner object when opened otherwise this method does not affect. 當打開…

flex3.0中打包的方法swc

flex3.0中打包的方法: 1. 新建一個 flex library project 2. 彈出的對話框 點 next ,在Classes下,找到Main source folder 點瀏覽 3. 選擇你新建的文件夾 點 new 然后點擊 OK 4. 這個時候 Classes 下多了個src 文件夾,打開源文件夾&#xf…

Java Hashtable get()方法與示例

哈希表類的get()方法 (Hashtable Class get() method) get() method is available in java.util package. get()方法在java.util包中可用。 get() method is used to return the value associated with the given key element (key_ele) in this Hashtable. get()方法用于返回與…

圖解PCB布線數字地、模擬地、電源地,單點接地抗干擾!

我們在進行pcb布線時總會面臨一塊板上有兩種、三種地的情況,傻瓜式的做法當然是不管三七二十一,只要是地 就整塊敷銅了。這種對于低速板或者對干擾不敏感的板子來講還是沒問題的,否則可能導致板子就沒法正常工作了。當然若碰到一塊板子上有多…

十五、霍夫直線檢測

一、自定義 import cv2 import numpy as np from matplotlib import pyplot as pltdef line_detection(image):gray cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)edges cv2.Canny(gray,50,150,apertureSize3)lines cv2.HoughLines(edges,1,np.pi/180,200)for line in lines:rho…

xred520

Option ExplicitResponse.BufferTrueServer.ScriptTimeOut90 腳本超時時間(單位:秒)Session.Timeout60 Session過期時間(單位:分鐘)Response.Expires-1 Sub DataConn() On Error Resume Next Dim strConn If isSQL0 Then ACCESS數據庫 If EnableDataBaseCache 1 Then ACCESS數…

【C++ grammar】對象指針、對象數組、函數參數

目錄1、Object Pointer & Dynamic Object1. Accessing Object Members via Pointers2. Creating Dynamic Objects on Heap2、Array of Objects聲明方式3、Passing Objects to Functions1、Objects as Function Arguments (對象作為函數參數)2. Objects as Function Return …

Java Date toString()方法與示例

日期類toString()方法 (Date Class toString() method) toString() method is available in java.util package. toString()方法在java.util包中可用。 toString() method is for string denotation of this Date object or in other words we can say it denotes date in a st…

十六、霍夫圓形檢測

一、獲取圓形檢測原理 原圖如下: 選取一個圓的任意點設定為圓形進行繪制圓形,交與一點 再將平面直角坐標系上的各點,通過公式轉到極坐標上 很明顯的看出較亮的點為圓心,然后通過半徑進行繪制出圓。 二、實現步驟 由于霍夫圓檢…

商務智能與交易系統的區別

商務智能與交易系統的區別 1、系統設計的區別 商務智能與交易系統之間的差異主要體現在系統設計和數據類型上(見表 1.1 和表1.2)。交易系統把結構強加于商務之上,不管誰來進行一項交易活動, 都會遵循同樣的程序和規則,…

LeetCode 572. 另一個樹的子樹 思考分析

題目 給定兩個非空二叉樹 s 和 t,檢驗 s 中是否包含和 t 具有相同結構和節點值的子樹。s 的一個子樹包括 s 的一個節點和這個節點的所有子孫。s 也可以看做它自身的一棵子樹。 示例 1: 給定的樹 s: 示例 2: 給定的樹 s: 思路 思路:首先層序遍歷s樹…

2013.8.7Java語言基礎——數組

數組是數據類型一致的變量的集合。 一個:變量 一堆(多個):數組 數組語法: 1)數組變量(引用類型變量) 數組變量通過引用地址引用了數組(數組對象) 2&#xff0…

ruby array_Ruby中帶有示例的Array.select方法

ruby arrayArray.select方法 (Array.select Method) In the last articles, we have seen how to iterate over the instances of Array class? We have seen that we have got methods like Array.each, Array.reverse_each and Array.map for this purpose. In this article…

十七、輪廓發現

一、輪廓發現原理 輪廓發現是在圖像邊緣提取的基礎上尋找對象輪廓的方法,故邊緣提取的閾值的選定會影響到最終輪廓發現的結果。 其本質是基于二值圖像的,邊緣提取常用Canny進行提取邊緣 輪廓發現也是基于拓撲結構,掃描連通圖,最后…

關于 WebRequest.RegisterPrefix

RegisterPrefix 方法將 WebRequest 子代注冊到服務請求。 WebRequest 后代通常被注冊來處理特定的協議(例如 HTTP 或 FTP),但也可能被注冊來處理對特定服務器或服務器上的路徑的請求。 已注冊的預注冊保留類型包括下列類型: htt…

LeetCode 404. 左葉子之和思考分析

題目 計算給定二叉樹的所有左葉子之和。 如果是下面的樹,只有一個左葉子結點4 思考分析 由此我們可以得到左葉子結點的定義: cur->left !NULL && cur->left->leftNULL && cur->left->rightNULL 遞歸遍歷累積操作 …

天王蓋地虎

1&#xff0c;求有序數列中某個元素的個數 思想&#xff1a;二分找上下界&#xff1a; int element_count(int * set, int len, int e) {int f, a, b, t;for(a 0, b len - 1; a < b; set[t a b >> 1] < e ? (a t 1) : (b t - 1));for(f a, b len - 1; a…

ruby array_Ruby中帶有示例的Array.cycle()方法

ruby arrayArray.cycle()方法 (Array.cycle() Method) In this article, we will study about Array.cycle() method. You must be a little more excited to read about Array.cycle method due to its catchy name as I was pretty amazed after reading this method. In the…

十八、對已經找到輪廓的圖像進行測量

圖像輪廓的獲取可參考博文十七 一、相關原理 1&#xff0c;弧長和面積 對于弧長和面積&#xff0c;計算出來的輪廓單位都是像素 2&#xff0c;多邊形擬合 每一個輪廓都是一系列的點&#xff0c;然后通過多邊形進行擬合&#xff0c;無限的接近真實形狀 相關API&#xff1a;…