2012-02-25 59 views
7

在Django中對於具有'管理員'權限的用戶實現具有額外功能的模板的最佳方式是什麼?Django - 向管理員顯示不同的模板

我不確定是否應該爲管理員創建一組完全不同的視圖,或者將其集成到我現有的視圖和模板中,如「如果用戶是管理員」。

Django有沒有一種標準的方法來做到這一點?

回答

2

如果您在模板上下文中可用的用戶,你可以做:F您使用RequestContext和你TEMPLATE_CONTEXT_PROCESSORS設置包含django.contrib.auth.context_processors.auth,這是默認

{% if user.is_active and user.is_staff %} 
    Only the admin will see this code. For example include some admin template here: 
    {% include "foo/bar.html" %} 
{% endif %} 

用戶將在你的模板中可用。請參閱authentication data in templates作爲參考。

6

這將只顯示,如果你是積極的和工作人員沒有聯繫的東西:

{% if request.user.is_active and request.user.is_staff %} 
    {% include "foo/bar.html" %} 
{% endif %} 

如果你想僅僅只爲管理員展示你要做的是:

{% if request.user.is_superuser %} 
    ADD your admin stuff there. 
{% endif %} 

大約差異這些字段here

2

我是一個維護視圖層(通常是關於MVC設計模式)的邏輯的倡導者。那麼爲什麼不使用裝飾器來根據用戶的特權將用戶引導到不同的視圖?在你的urls.py,定義管理員模式:

url(r'^admin/$', 'user.views.admin_index'), 
#do so for your other admin views, maybe more elegantly than this quick example 

然後定義一個裝飾來了一腳用戶,如果他們不是管理員

def redirect_if_not_admin(fn): 
def wrapper(request): 
    if request.user.is_staff(): 
     return fn(request) 
    #or user.is_superuser(), etc 
    else: 
     return HttpResponseRedirect('/Permission_Denied/') 
return wrapper 

而且在你的管理意見

@redirect_if_not_admin 
def index(request): 
##do your thing 

它比其他兩個答案更多的代碼,這是沒有錯的。這只是一個個人偏好,在視圖中保持混亂。