1、settings.py 中設置變量
2、存放到數據庫
如何在模板中直接使用全局變量
轉自:https://oomake.com/question/62799
1、使用中間件
如果這是您希望獲得的每個請求的值,模板,使用context processor更合適。 就是這樣:
- 在您的應用目錄中創建一個
context_processors.py
文件。假設我想在每種情況下都具有ADMIN_PREFIX_VALUE
值:from django.conf import settings # import the settings file def admin_media(request): # return the value you want as a dictionnary. you may add multiple values in there. return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
- 將你的上下文處理器添加到你的settings.py文件中:
TEMPLATES = [{ # whatever comes before 'OPTIONS': { 'context_processors': [ # whatever comes before "your_app.context_processors.admin_media", ], } }]
- 在您的視圖中使用
RequestContext
以在模板中添加上下文處理器。 render shortcut會自動執行此操作:from django.shortcuts import render def my_view(request): return render(request, "index.html")
- 最后,在您的模板中:
... <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a> ..
2、自定義模板標簽
@register.tag def value_from_settings(parser, token): try: # split_contents() knows not to split quoted strings. tag_name, var = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] return ValueFromSettings(var) class ValueFromSettings(template.Node): def __init__(self, var): self.arg = template.Variable(var) def render(self, context): return settings.__getattr__(str(self.arg))
然后你可以使用:
{% value_from_settings "FQDN" %}
可以在任何頁面上打印,而無需跳過上下文處理器環節。
Django 設置template的全局變量
相信許多Web開發者一定有那么一個需求,需要在所有的頁面上面顯示同樣的后台數據。比如:
- 用戶信息: 當一個用戶登陸成功后肯定希望每個頁面都能顯示當前登陸用戶的信息。
- 一些由后台生成的標簽(或者說索引): 用戶可以通過點擊標簽進行不同頁面跳轉,但是每個頁面中都會有這些標簽。
這個時候如果在view.py文件中的每一個方法里組織對應的數據用於頁面解析,那絕對是十分蛋疼的事情,
這個時候我們就需要把這些數據保存成全局變量的形式讓他可以輕松渲染到每一個頁面。
Django
settings.py
文件里面有這樣一個配置。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
注意到 OPTIONS.context_processors 里面有4條信息,其實每一條信息都對應一個函數,這里的原理是設置每一個函數的返回值作為Template的全局變量
,而最簡單的函數request他是這樣的
from django.template import context_processors.py
def request(request): return {'request': request}
它只是簡單地返回一個字典 {'request': request} 這就不難理解為什么在Django的模板系統里面,所有的Template我們都可以直接訪問request.user來
獲取對應的用戶了吧。由於request被設置成全局變量,以字典的形式傳到后台去了。
依樣畫葫蘆,我們也可以編寫個腳本。:
global_variable.py
from .models import Classification from taggit.models import Tag def setting(request): classifications = Classification.objects.all() tags = Tag.objects.all() content = {"classifications": classifications, "tags": tags} return content
這只是我blog系統的一小部分代碼,用於獲取所有的分類,以及所有的Tag標簽,方便搜索。如果global_variable.py文件坐落在
BASE_DIR(這個用過Django的朋友應該都知道了吧.這個變量是在settings.py文件里面)/blog/page目錄下,則需要設置
settings.py
中的
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # 加上這句 'blog.page.global_variable.setttings' ], }, }, ]
就OK 了,這樣就可以在templates里面引用tags, 和classifications變量了.很感謝你有耐心看到這里,不過希望你能繼續往下看,或許能對你有幫助.
你可能會遇到的坑
下面是我寫的一段代碼
views.py
def detail(request, id): article = get_object_or_404(Article, pk=id) template = loader.get_template("page/detail.html") context = RequestContext(request, {'article': article}) return HttpResponse(template.render(context))
但是Django1.9給了我這樣的提示
RemovedInDjango110Warning: render() must be called with a dict, not a RequestContext.說10以后將會丟棄RequestContext
理所當然,我把代碼改成下面這樣
def detail(request, id): article = get_object_or_404(Article, pk=id) template = loader.get_template("page/detail.html") context = {'article': article} return HttpResponse(template.render(context))
接着災難就發生了,雖然說避開了1.9的警告,不過上面的代碼,沒有把request包裝到RequestContext()里面解析到模板中去,這就會有一個問題.
所有的settings里面設置的全局變量都不起作用了,他根本就不會去解析全局變量,這個坑,坑了我幾個小時.所以最好的方法是采取Django給我們
的偷懶方法.
from django.shortcuts import render
def detail(request, id): article = get_object_or_404(Article, pk=id) return render(request, "page/detail.html", context)
因為據說RequestContext()將在1.10被丟棄,考慮到兼容性,用它提供的接口最好不過啦.
記得一定要在view的方法里面把request傳到后台哦,不然只傳字典的話,全局變量那便會得不到解析的.
作者:lanzhiheng
鏈接:https://www.jianshu.com/p/d90469a527d4
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。