gpt4 book ai didi

Django DetailView get_context_data

转载 作者:行者123 更新时间:2023-12-04 22:28:18 27 4
gpt4 key购买 nike

我是 Django 的新手。有一个 html 页面 (project_details) 应该显示项目的标题和任务,但只显示项目的标题,而不是任务。任务存在,问题出在过滤器上!!!

View .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

模型.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'),]

project_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 %}

对不起,我的英语不好。

最佳答案

Project是模型类,所以这样做 (list=Project)没有意义。

如果要访问详细 View 中的对象 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 %}

关于Django DetailView get_context_data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45679155/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com