简体   繁体   English

Django DetailView get_context_data

[英]Django DetailView get_context_data

I'm new in Django. 我是Django的新手。 There is a html page (project_details) which should show the title and the tasks of the project, but shows only the title of the project, not the tasks. 有一个html页面(project_details)应该显示项目的标题和任务,但只显示项目的标题,而不是任务。 The tasks exists, the problem is the filter!!! 任务存在,问题是过滤器!

views.py The error is here 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 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 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 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 %}

Sorry for my bad English. 对不起,我的英语不好。

Project is the model class, so doing (list=Project) doesn't make sense. Project是模型类,所以做(list=Project)没有意义。

If you want to access the object in the detail view's get_context_data method, you can use self.object : 如果要在详细视图的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

However, you don't actually have to override the get_context_data method at all. 但是,实际上您根本不必覆盖get_context_data方法。 In your template, you can follow the relationship backwards from a project to get its tasks: 在模板中,您可以从项目向后跟踪关系以获取其任务:

{% for task in object.task_set.all %}
  <li>{{task}}</li>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM