2014-01-21 66 views
0

我想限制用戶在Django中訪問某些頁面直到他們登錄。下面的代碼工作正常,除了我用來傳遞查詢設置它可以顯示我的所有書籍,而且這種方法不能像那樣工作。在Django中傳遞在保護視圖中設置的查詢

新的視圖類(需要登錄,但沒有查詢集送?)

class IndexView(TemplateView): 
    template_name = 'quotes/index.html' 
    args = Book.objects.all() 
    @method_decorator(login_required) 
    def dispatch(self, args): 
     return super(IndexView, self).dispatch(args) 

我無法弄清楚如何使用這種類型的視圖一起傳遞我的查詢Book.objects.all()。我的看法過去看起來像下面。正如你所看到的,它返回了一個由模板使用的查詢集。 我正在使用此Django documentation來嘗試並提供登錄功能。

以前使用的視圖類(無需登錄):

class IndexView1(generic.ListView): 
    template_name='quotes/index.html' 
    context_object_name = 'book_list' 
    def get_queryset(self): 
     """Return all the book objects""" 
     return Book.objects.all() 
+0

我不明白你在這裏做了什麼。爲什麼你不能繼續使用ListView子類並在那裏重寫'dispatch()'?或者爲什麼你不能在urlconf中使用login_required包裝器,如[文檔]中所示(https://docs.djangoproject.com/en/1.6/topics/class-based-views/intro/#decorating-class基於視角)? –

+0

看起來我被文檔弄糊塗了。我沒有意識到你可以使用這種派遣。 – lorless

回答

0

兩個基於類的觀點,你剛纔提到ListView(以上)和TemplateView是不等價的。你可以像以前一樣使用ListView派生類,如下所示:

class IndexView(generic.ListView): 
    template_name='quotes/index.html' 
    context_object_name = 'book_list' 

    @method_decorator(login_required) 
    def dispatch(self, args): 
     return super(IndexView, self).dispatch(args) 

    def get_queryset(self): 
     """Return all the book objects""" 
     return Book.objects.all() 
+0

感謝這個例子,這解釋了很多。我是否認爲只有當用戶沒有登錄時調用調度,但在用戶已經登錄時沒有調用調度? – lorless

+0

每個Web請求都通過[dispatch](https://docs.djangoproject.com/en/1.6/ref/class-based-views/base/#django.views.generic.base.View.dispatch)。所以它是增加額外安全性的合適地點。 – arocks

+0

當我在我的url中使用一個id時,我得到這個錯誤dispatch()得到了一個意外的關鍵字參數'pk',即使我登錄了。是否有解決方法? – lorless