尝试使用基于 class 的视图迭代 Django 中的模型,但出现错误 Project object is not iterable

Trying to iterate over a model in Django with class based views but getting the error Project object is not iterable

我为 models.py

使用了以下代码
class Project(models.Model):
    name = models.CharField(max_length=20,null=True)
    description = models.TextField(null=True)
    clientid = models.ForeignKey(Client, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.name
        
    def get_absolute_url(self): # new
        return reverse('projectdetail', args=[str(self.id)])

这是 views.py

的代码
class ProjectDetailView(DetailView):
    model = Project
    template_name = 'projectdetail.html'
    fields='__all__'

这是我正在使用的模板

{% extends 'base.html' %}

{% block content %}
    
    {% if project %}
       There are {{ project|length }} records:
    {% for i in project %}
    <div class="project-entry">
        <h2>{{ i.id }}</h2>
        <p>{{ i.name }} </p>
        <p>{{ i.description }} </p>
        <p>{{ i.clientid }} </p>
   {% endfor %}
{% else %}
   There are no records in the system
{% endif %}
    </div>
    
{% endblock content %}

我收到错误

TypeError at /client/1/projectexisting
'Project' object is not iterable
Request Method: GET
Request URL:    http://02ccd1dfc89b4b71b62f894adef16c07.vfs.cloud9.us-east-2.amazonaws.com/client/1/projectexisting
Django Version: 2.1
Exception Type: TypeError
Exception Value:    
'Project' object is not iterable
Exception Location: /home/ec2-user/.local/lib/python3.7/site-packages/django/template/defaulttags.py in render, line 165
Python Executable:  /usr/bin/python3
Python Version: 3.7.10
Python Path:    
['/home/ec2-user/environment/cons_mgmt/cons_mgmt',
 '/usr/lib64/python37.zip',
 '/usr/lib64/python3.7',
 '/usr/lib64/python3.7/lib-dynload',
 '/home/ec2-user/.local/lib/python3.7/site-packages',
 '/usr/local/lib64/python3.7/site-packages',
 '/usr/local/lib/python3.7/site-packages',
 '/usr/lib64/python3.7/site-packages',
 '/usr/lib/python3.7/site-packages']
Server time:    Tue, 20 Jul 2021 19:55:29 -0600
Error during template rendering
In template /home/ec2-user/environment/cons_mgmt/cons_mgmt/templates/base.html, error at line 6

'Project' object is not iterable

如果我取出 for 循环,我就能看到数据,但我只能看到第一个条目,第二个条目在另一个客户页面中。

我更愿意将上下文显式发送到模板中,以便移动是透明的...像这样,

class ProjectDetailView(DetailView):
  model = Project
  template_name = 'projectdetail.html'

  def get_context_data(self, **kwargs):
    context = super(ProjectDetailView, self).get_context_data(**kwargs)
    context['project'] = Project.objects.all()    
    return context

现在您可以遍历项目对象...

保持你的 models.py 模板 html 不变,并用以下代码替换 views.py [不要忘记保留备份],然后尝试执行。让我知道它是否适合你。

#views.py
from .models import Project
def ProjectDetailView(request):
    projectdetails = Project.objects.all()
    context = {
        'project': projectdetails
    }
    return render(request, 'projectdetail.html', context)