2013-10-22 32 views
1

我寫了我的Django的網站單獨的應用程序名爲restricted,並駐留在Django的應用要求組

http://localhost:8000/restricted/ 

我希望能夠限制訪問這一整個應用到特定組的唯一成員(讓我們稱它爲「限制組」)。

有沒有辦法輕鬆做到這一點?也許在urls.conf文件中?該應用程序充滿了基於班級的列表視圖(30+),所以我不願意將這種檢查應用於我的view.py文件中的每個視圖。

EDIT:爲了解決這個問題,我添加了一個函數到我的視圖:

def group_check(user): 
    if user: 
     return user.groups.filter(name='Restricted').count() >= 1 
    return False 

對於任何普通視圖(例如index),我把裝飾:

@user_passes_test(group_check) 
def index(request): 
    return render_to_response('listview/index.html') 

對於我的班級列表視圖:

class MyListView1(ListView): 
    context_object_name = "objs" 
    queryset = MyList.objects.all() 
    template_name = "listviews/mylist.html" 

    @method_decorator(user_passes_test(group_check)) 
    def dispatch(self, *args, **kwargs): 
     return super(MyListView1, self).dispatch(*args, **kwargs) 

對於那些與重新定義的查詢集:

class MyListView1_Custom(ListView): 
    context_object_name = "obj" 
    template_name = "listviews/mylist_custom.html" 

    @method_decorator(user_passes_test(group_check)) 
    def get_queryset(self): 
     self.obj1 = get_object_or_404(MyList, id__iexact=self.args[0]) 
     self.context = {} 
     self.context['custom'] = self.obj1 
     return self.context 

當然,這需要你輸入:

from django.utils.decorators import method_decorator 
from django.contrib.auth.decorators import user_passes_test 

測試後,我的結論是,這是基於羣體保護的意見適當的方法。任何不屬於「受限制」組的用戶都會重定向到默認登錄頁面。

你可以在Django的文檔頁面找到更多信息:user_passes_test,它也描述瞭如何將它們重定向到不同的位置(如果你願意,可以使用它重定向到404)。

回答

1

總之 - 你不能在urls conf中做。原因很簡單。這些文件在Django啓動時被編譯並且不會被動態解釋。

相反,你可以建立一個類似login_required類似restricted_required的定製修飾器,由django提供,並在需要的任何地方使用。