我在视图页面上有这个方法。它工作正常,并正确显示所有内容,但我想将其转换为通用列表视图,以便我可以应用分页。
这是函数:`
#views.py
def index(request):
all_artists = Artist.objects.all()
all_songs = Song.objects.all()
all_albums = Album.objects.all()
return render(request, 'index.html', {'all_albums':all_albums,'all_songs':all_songs, 'all_artists':all_artists})
所以我遵循了一些教程并最终得到了这个:
#new views.py
class IndexView(ListView):
template_name = 'index.html'
context_object_name = 'home_list'
queryset = Artist.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['all_artists']=Artist.objects.all()
context['all_songs']=Song.objects.all()
context['all_albums']=Album.objects.all()
虽然它编译没有任何错误,但是当我渲染页面时,上下文对象不会被渲染。 非常感激您的帮忙! 三江源
EDIT(13-APR-17): 感谢你们!最后它进行了一些修改。
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'home_list'
queryset = Artist.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['all_artists']=Artist.objects.all()
context['all_songs']=Song.objects.all()
context['all_albums']=Album.objects.all()
return context
enter code here
enter code here
答案 0 :(得分:2)
urls.py 在您的django应用程序的urls.py中,您需要包含一个引用您的视图的URL,并将此urls.py包含在您的django项目主urls.py中。
#urls.py
from django.conf.urls import url
from .views import IndexView
urlpatterns = [
url(r'^path/$', IndexView.as_view(), name="index"),
]
然后在views.py中覆盖变量paginate_by
#views.py
class IndexView(ListView):
template_name = 'index.html'
context_object_name = 'home_list'
queryset = Artist.objects.all()
paginate_by = 10 # Number of objects for each page
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['all_artists']=Artist.objects.all()
context['all_songs']=Song.objects.all()
context['all_albums']=Album.objects.all()
return context
最后在你的index.html中 添加分页{%pagination_for page_obj%}
{% block content %}
<!--some content -->
<!--begin paginator -->
{% pagination_for page_obj %}
<!--end paginator-->
{% endblock %}
答案 1 :(得分:0)
你的get_context_data()需要返回上下文。因此,如果这是您的确切代码,则需要向其添加返回上下文