2016-06-14 77 views
1

在Rails中,如果我想設置一個「上下文」,該上下文基本上是每個視圖需要的對象,例如登錄用戶的用戶對象,或者說存儲/帳戶/位置對象,我如何在django框架中的每個視圖上都可用?如何在django中設置「上下文」類型對象

在Rails我會做這樣的事情:

class BaseController 
    before_action :setup_context 


    def setup_user 
    @user = # load user from db 
    @location = # load location for user 
    end 
end 

class HomeController < BaseController 

    def index 
    # I now can use the variables @user and @location 
    end 

end 

確實Django的這些類型,我可以加載的對象,並在我的所有視圖中使用它們的事件?

+0

它只是你需要訪問的用戶嗎?如果是這樣,那麼'request.user'是要訪問視圖方法的對象。 –

+0

@ShangWang不用用戶,我通常這樣做:context.user context.location context.account,即添加到上下文對象的所有東西。 –

+1

這是上下文處理器的用途,請參閱http://stackoverflow.com/questions/2893724/creating-my-own-context-processor-in-django或http://stackoverflow.com/questions/2246725/ django-template-context-processors - 具體說就是Django如何在請求中添加'user'對象,並且如果你需要的不僅僅是內建的,你可以自己編寫。 –

回答

0

如果我正確理解你的問題,我認爲你正在試圖做這樣的事情。我對Django本人還相當缺乏經驗,所以請帶上一點鹽。

基本例如:

views.py

from django.shortcuts import render 
from exampleapp.models import User # User object defined in your models.py 

def index(request): 
    context = { 'users': User.objects.all() } 
    return render(request, 'exampleapp/example.html', context) 

example.html的

{% if users %} 
    {% for user in users %} 
     <p>{{ user.name }}</p> 
    {% endfor %} 
{% else %} 
    <p>No users.</p> 
{% endif %} 

我道歉,如果我錯過了你的問題的標誌。

相關問題