emc*_*cee 2 python generics django templates views
嗨,我正在尝试创建一个投资组合页面,我在其中一个项目详细信息下显示项目列表.使用通用列表视图我可以显示项目列表.
在我的项目细节中,我可以使用DetailView来显示项目.但是我无法在详细信息下面的项目详细信息中显示项目列表.
我扩展了基本模板,因此列表和项目的模板块存在于不同的html文件中.所以我认为问题不在我的模板中.
views.py
class ProjectView(generic.DetailView):
template_name = 'portfolio/project_detail.html'
def get_queryset(self):
return Project.objects.filter(pub_date__lte=timezone.now())
class IndexView(generic.ListView):
template_name = 'portfolio/index.html'
context_object_name = 'project_list'
def get_queryset(self):
return Project.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
Run Code Online (Sandbox Code Playgroud)
urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),,
url(r'^project/(?P<pk>[0-9]+)/$', views.ProjectView.as_view(), name='project]
Run Code Online (Sandbox Code Playgroud)
在ProjectView中添加此功能:
def get_context_data(self, **kwargs):
context = super(ProjectView , self).get_context_data(**kwargs)
context['projects'] = Project.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
return context
Run Code Online (Sandbox Code Playgroud)
这样,您就可以访问模板中的项目列表 {{projects}}
在这里阅读更多