【发布时间】:2020-03-06 12:13:30
【问题描述】:
我有以下 2 个模型 - ToDoList 和 Tasks。 Tasks 具有模型 ToDoList 的外键。在我的 Detailview 中,我只想显示已发布的任务 (status="published")。
我试图覆盖视图的获取上下文数据。这行得通。但它根本没有在 Detailview 中显示任何任务实例,即使我将例如 1 个任务设置为“已发布”。
我也尝试在模板中做过滤条件。我想这是不可能的?我或多或少地确定过滤条件必须出现在查询集中。
class ToDoList(TimeStamp):
class STATUS(models.TextChoices):
PUBLISHED = "published", "Published"
TRASH = "trash", "Trash"
WORKINGDRAFT = "workingdraft", "Workingdraft"
headline = models.CharField(max_length=200)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED)
def __str__(self):
return self.headline
def get_absolute_url(self):
return reverse('notepad:todo_detail', args=[str(self.id)])
class Tasks(TimeStamp):
class STATUS(models.TextChoices):
PUBLISHED = "published", "Published"
TRASH = "trash", "Trash"
WORKINGDRAFT = "workingdraft", "Workingdraft"
todos = models.CharField(max_length=250)
todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE, related_name='tasks')
status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED)
def __str__(self):
return self.todos
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponseRedirect
from django.forms.models import inlineformset_factory
from django.views.generic import ListView, DetailView, TemplateView
from django.views.generic.edit import CreateView
from django.urls import reverse
from django.urls import reverse_lazy
from .models import ToDoList, Tasks
from .forms import ToDoListForm
class ToDoDetailView(DetailView):
model = ToDoList
template_name = 'notepad/notepad_detail.html'
def get_context_data(self,**kwargs):
context = super(ToDoDetailView,self).get_context_data(**kwargs)
context['tasks_published'] = self.object.tasks.filter(status="published")
return context
def get_object(self):
object = super(ToDoDetailView, self).get_object()
object.num_tasks = object.tasks.all().count()
return object
模板
<!-- templates/books/book_detail.html -->
{% extends 'base.html' %}
{% block title %}{{ object.headline }}{% endblock title %}
{% block content %}
<div class="book-detail">
<h2><a href="">{{ object.headline }}</a></h2>
<p>Author: {{ object.author }}</p>
<p>Created at: {{ object.created }}</p>
<p>Total Tasks: {{ object.num_tasks }}</p>
<div>
<h3>Tasks</h3> <ul>
{% for todo in tasks_published %}
<li>{{ todo.todos }}</li>
{% endfor %}
</ul> </div>
</div>
<a class="btn btn-primary"
href="{% url 'notepad:todo_list' %}" role="button">
Back to ToDo List
</a> </p>
{% endblock content %}
任何帮助将不胜感激。 非常感谢您的时间和支持。
【问题讨论】:
标签: django django-views django-templates