Python django ImageField未显示,引发错误
我有一个模型,其中有图像名称、图像描述和图像。我想使用这些字段显示一个div,其中包含模型中每一行的图像描述和名称以及缩略图。现在,当我尝试渲染模板时,我得到:Python django ImageField未显示,引发错误,python,django,Python,Django,我有一个模型,其中有图像名称、图像描述和图像。我想使用这些字段显示一个div,其中包含模型中每一行的图像描述和名称以及缩略图。现在,当我尝试渲染模板时,我得到: TypeError: 'ImageFieldFile object is not subscriptable During handling of the above exception another error occured: ImportError: No module named 'backends
TypeError: 'ImageFieldFile object is not subscriptable
During handling of the above exception another error occured:
ImportError: No module named 'backends'
代码:
Models.py
class PictureType(models.Model):
name = models.CharField(max_length = 150)
description = models.CharField(max_length = 1000)
image = models.ImageField(upload_to='AppName/images/')
views.py
class indexView(generic.ListView):
model = PictureType
template_name = 'index.html'
index.html
{% for visual in object_list %}
<div class="col-sm-4">
<div class="thumbnail">
<a href="#" class="">
<div align="center" class={{ visual.name }}>
<h4 class="">{{ visual.name }}</h4>
<p class="">{{ visual.description }}
</p>
</div>
<img src= "{{ visual.image.url }}" alt="..." class="">
</a>
</div>
</div>
{% endfor %}
url.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', indexView.as_view(), name = 'index'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
更新:
当我改变时:
<img src= "{{ visual.image.url }}" alt="..." class="">
到
我没有发现上面的错误,但是图像也没有通过,它们看起来是这样的:听起来好像您试图在代码中的某个地方导入“后端”模块,但它在python路径中不存在。
希望这有帮助。您必须从数据库中检测图像URL,并将其作为上下文数据类型传递到HTML模板文件 首先,你必须确保你已经安装了枕头库 (pip instal枕头) 并将静态文件加载到index.html文件
{%load static%}-在HTML开始时使用此代码 然后将view.py函数更改为:
class indexView(generic.ListView):
model = PictureType
users = PictureType.objects.all()
args = {'users':users}
template_name = 'index.html',args
或者,传递数据的更好方法是将视图更改为函数。
我有'BACKEND':'django.template.backends.django.DjangoTemplates',在我的settings.py中。如果你想导入它,它需要准确地拼写为'backends'。
<img src= "{{ visual.image }}" alt="..." class="">
class indexView(generic.ListView):
model = PictureType
users = PictureType.objects.all()
args = {'users':users}
template_name = 'index.html',args
def indexView(request):
model = PictureType
users = PictureType.objects.all()
args = {'users':users}
return render(request,"index.html", args)