2013-08-02 53 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 –