2017-08-14 97 views
0

我是新的Django。有一個html頁面(project_details)應該顯示項目的標題和任務,但只顯示項目的標題,而不顯示任務。任務存在,問題是過濾器!Django DetailView get_context_data

views.py的錯誤是在這裏

from .models import Project,Task 
from django.views.generic import ListView, DetailView 

class ProjectsList(ListView): 
    template_name = 'projects_list.html' 
    queryset= Project.objects.all() 

class ProjectDetail(DetailView): 
    model = Project 
    template_name = 'projects_details.html' 

    def get_context_data(self, **kwargs): 
    context = super(ProjectDetail, self).get_context_data(**kwargs) 
    ## the context is a list of the tasks of the Project## 
    ##THIS IS THE ERROR## 
    context['tasks'] = Task.object.filter(list=Project) <---->HERE ((work with Task.object.all())) 

    return context 

models.py

class Project(models.Model): 
    title = models.CharField(max_length=30) 
    slug = AutoSlugField(populate_from='title', editable=False, always_update=True) 

class Task(models.Model): 
    title = models.CharField(max_length=250) 
    list = models.ForeignKey(Project) 
    slug = AutoSlugField(populate_from='title', editable=False, always_update=True) 

urls.py

from django.conf.urls import url 
from .models import Project 
from .views import ProjectsList, ProjectDetail 

urlpatterns = [ 
    url(r'^$', ProjectsList.as_view(), name='project_list'), 
    url(r'(?P<slug>[\w-]+)/$',ProjectDetail.as_view() , name='project_details'),] 

projects_details.html

{% extends './base.html' %} 
{% block content %} 

<div> 
<a href={{ object.get_absolute_url }}> 
<h4> {{object.title}} </h4> 
</a> 
<ul> 
{% for task in tasks %} <----> NO OUTPUT <li> 
<li> {{task}}</li> 
{% endfor %} 
</ul> 
</div> 
{% endblock content %} 

對不起,我的英語不好。

回答

2

Project是模型類,所以做(list=Project)沒有意義。

如果您要訪問的詳細視圖的get_context_data方法的對象,你可以使用self.object

def get_context_data(self, **kwargs): 
    context = super(ProjectDetail, self).get_context_data(**kwargs) 
    context['tasks'] = Task.objects.filter(list=self.object) 
    return context 

但是,你實際上並沒有在所有覆蓋get_context_data方法。在您的模板中,您可以沿着項目後退關係獲取其任務:

{% for task in object.task_set.all %} 
    <li>{{task}}</li> 
{% endfor %} 
相關問題