如何解决尝试使用基于类的视图迭代 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 举报,一经查实,本站将立刻删除。