我有一个模型,我有一个图像名称,图像描述和图像。我想使用这些字段显示带有图像描述的div和名称以及模型中每行的缩略图。现在,当我尝试渲染我得到的模板时:
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 %}
settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = '/media/'
urls.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="">
到
<img src= "{{ visual.image }}" alt="..." class="">
答案 0 :(得分:0)
听起来好像是在尝试在代码中的某处导入'后端'模块,但它在python路径中不存在。
希望这有用。
答案 1 :(得分:0)
您必须从数据库中保护图像URL,并将其作为上下文数据类型传递到HTML模板文件。
首先,您必须确保已经安装了枕头库 (pip枕头)
并将静态文件加载到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
def indexView(request):
model = PictureType
users = PictureType.objects.all()
args = {'users':users}
return render(request,"index.html", args)