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

如何解决尝试使用基于类的视图迭代 Django 中的模型,但得到错误 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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?