2012-11-08 21 views
0

我有這樣一個問題,我GOOGLE了很多,閱讀有關decoratorsmiddleware,但我沒有遇到如何更好地解決我的問題。django:在視圖開始工作之前獲取基本變量

我有基本模板base.html和模板template1.htmltemplate2.html擴展爲base.html

base.html有一些通用塊,這是template1.htmltemplate2.html需要。 這個塊是與dinamic數據,所以我必須在每個視圖中獲取該塊的數據,然後渲染模板。

,比如我有2 views

@render_to("template1.html") 
def fun_1(request): 
data = getGeneralData() 
#...getting other data 
return { 
     "data" : data, 
     "other" : other_data, 
} 

@render_to("template2.html") 
def fun_2(request): 
data = getGeneralData() 
#...getting other data 
return { 
     "data" : data, 
     "other2" : other_data2, 
} 

所以一般我需要這個getGeneralData在我所有的views的,有我打電話getGeneralData()功能在每一個我認爲我也可以做這將讓general_data任何功能並在任何視圖獲取自己的數據之前將其渲染爲模板?

您能否給我提供一個例子的代碼或給我一個好的鏈接如何做得更好?

回答

1

建議您自己編寫context processor並從那裏返回所需的上下文數據。

例子:

custom_context_processor.py

def ctx_getGeneralData(request): 
    ctx = {} 
    ctx['data'] = getGeneralData() 
    return ctx 

在設置文件,更新TEMPLATE_CONTEXT_PROCESSORS'custom_context_processor.ctx_getGeneralData'

1

你有沒有考慮過使用Django的基於類的看法?最初它們有點難以使用,但它們使這種事情變得非常簡單。下面是我如何使用基於類的意見重寫基於函數的觀點:

# TemplateView is a generic class based view that simply 
# renders a template. 
from django.views.generic import TemplateView 


# Let's start by defining a mixin that we can mix into any view that 
# needs the result of getGeneralData() in its template context. 


class GeneralContextDataMixin(object): 
    """ 
    Adds the result of calling getGeneralData() to the context of whichever 
    view it is mixed into. 
    """ 

    get_context_data(self, *args, **kwargs): 
     """ 
     Django calls get_context_data() on all CBVs that render templates. 
     It returns a dictionary containing the data you want to add to 
     your template context. 
     """ 
     context = super(GeneralContextDataMixin, self).get_context_data(*args, **kwargs) 
     context['data'] = getGeneralData() 
     return context 


# Now we can inherit from this mixin wherever we need the results of 
# getGeneralData(). Note the order of inheritance; it's important. 


class View1(GeneralContextDataMixin, TemplateView): 
    template_name = 'template1.html' 


class View2(GeneralContextDataMixin, TemplateView): 
    template_name = 'template2.html' 

當然,你也可以寫你自己的上下文處理器羅漢說。事實上,如果你想將這些數據添加到全部你的意見,我建議你這樣做。

無論你最終做什麼,我都會敦促你看看基於類的觀點。他們使很多重複性任務變得非常簡單。

進一步閱讀: