2016-08-17 28 views
-2

我有一個函數可以獲取我的views.py文件中的一些基本信息,我試圖通過讓它返回一個字典來更新每個頁面的上下文。但是,在render()函數的上下文字典上使用.update()似乎不起作用。不能在視圖中的Django上下文中使用.update()函數嗎?

下面是我在做什麼:

def getBaseInfo(): 
    allPages = list(Page.objects.all()) 
    primaryPages = allPages[:5] 
    secondaryPages = allPages[5:] 
    return {'p':primaryPages, 'p2':secondaryPages} 

def index(request): 
    return render(request, 'pages/index.html', {}.update(getBaseInfo())) 

但是,沒有發到我的模板。提前致謝!

編輯:我使用Python 2.7.11

+1

https://docs.python.org/3/library/stdtypes.html?highlight=update#dict.update 請注意:「Return'None'」部分。 Python不是javascript,更新方法不會返回字典,你所做的事情沒有意義。爲什麼不簡單地將'getBaseInfo()'作爲上下文來傳遞? – Wolph

+0

@Wolph,我不知道.update()返回'None'!感謝那。我無法傳遞'getBaseInfo()'作爲上下文,因爲我的Django應用程序使用Python 2,它不允許通過在字典中返回值更新字典('{getBaseInfo()}'不會成爲'{'p ':[],'p2':[]}',它只是一個沒有值的鍵字典) –

+1

'{getBaseInfo()}'不會變成'{'p':[],'p2 ':[]}'但'getBaseInfo()'確實。 'getBaseInfo()'已經返回一個字典,所以不需要轉換它。它可以作爲上下文直接使用 – Wolph

回答

2

首先,如果你想使用基本詞典和對象添加到您應該明確地這樣做:

def index(request): 
    context = getBaseInfo() 
    context.update({'otherkey': 'othervalue'}) 
    # or 
    context['otherkey'] = 'othervalue' 
    return(...) 

然而,有沒有必要做這個的。 Django已經爲您提供了一種自動提供共享上下文的方式,這是一個context processor

其實你getBaseInfo()功能已經幾乎上下文處理器 - 它只是需要接受request參數 - 所以你只需要把它添加到列表context_processors在模板中設置。然後全部您的模板將自動從該函數獲取值。

+0

感謝您讓我知道上下文處理器!我是Django的新手,仍在學習 - 這看起來正是我需要的! –

1

你應該做這樣的事情:

def index(request): 
    allPages = list(Page.objects.all()) 
    primaryPages = allPages[:5] 
    secondaryPages = allPages[5:] 
    return render(request, 'pages/index.html', {'p':primaryPages, 'p2':secondaryPages}) 

其他選項應該是使getBaseInfo的可重用性和DRY目的@property,或使查看基於類的模板視圖並將可重用代碼定義爲mixin。我更喜歡後者,但這完全是個人選擇的問題。

相關問題