2013-08-02 127 views
4

我第一次使用基於類的視圖。我無法低估如何使用基於類的視圖,我將實施django-endless-pagination Twitter樣式分頁。django - 基於類的視圖例子

我可以舉一個例子說明如何去做這件事嗎?

這是我的看法:

class EntryDetail(DetailView): 
    """ 
    Render a "detail" view of an object. 
    By default this is a model instance looked up from `self.queryset`, but the 
    view will support display of *any* object by overriding `self.get_object()`. 
    """ 
    context_object_name = 'entry' 
    template_name = "blog/entry.html" 
    slug_field = 'slug' 
    slug_url_kwarg = 'slug' 

    def get_object(self, query_set=None): 
     """ 
     Returns the object the view is displaying. 

     By default this requires `self.queryset` and a `pk` or `slug` argument 
     in the URLconf, but subclasses can override this to return any object. 
     """ 
     slug = self.kwargs.get(self.slug_url_kwarg, None) 
     return get_object_or_404(Entry, slug=slug) 
+0

爲什麼'DetailView'與分頁有什麼關係?你只有1個對象,就是它 –

+0

你想使用ListView。您可能會發現此問題有幫助:http://stackoverflow.com/questions/5907575/how-do-i-use-pagination-with-django-class-based-generic-listviews – meshy

回答

3

因爲這是一個很寬泛的問題,我想現在的幾個解決方案分頁結合起來。

1.使用通用ListView

from django.views.generic import ListView 

class EntryList(ListView): 
    model = Entry 
    template_name = 'blog/entry_list.html' 
    context_object_name = 'entry_list' 
    paginate_by = 10 

這將是更快的方式僅僅使用urls.py

url(r'^entries/$', ListView.as_view(model=Entry, paginate_by=10)) 

所以基本上你不需要在這個Django的無端分頁解。只有urls.py

from endless_pagination.views import AjaxListView  
class EntryList(AjaxListView): 
    model = Entry 
    context_object_name = 'entry_list' 
    page_template = 'entry.html' 

或更快的(再次):

from endless_pagination.views import AjaxListView 

url(r'^entries/$', AjaxListView.as_view(model=Entry)) 

參考您可以檢查模板,這裏的例子:How do I use pagination with Django class based generic ListViews?

2.使用Django的無端分頁的AjaxListViewhttp://django-endless-pagination.readthedocs.org/en/latest/generic_views.html

如果有人知道不同的溶膠請注意。

+0

我不明白'paginate_by = 10 ListView示例。 Django文檔沒有解釋這一點。哪些代碼應該評估'paginate_by = 10'? – guettli

+1

'ListView'子類'MultipleObjectMixin'。你可以在這裏查看關於分頁的文檔:https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin –