[英]Django; display problems for image of model object passed to template from view
使用django admin創建了一個具有名稱,描述和圖像的新項目,並附加了圖像,我看到該圖像在上傳時彈出到服務器上的媒體文件夾中。 我將項目從視圖傳遞到模板。 項目名稱,描述顯示在網站上,但圖像('image.jpg')沒有顯示。 有任何想法嗎? 也許nginx導致圖像隱藏起來? 我正在使用nginx,gunicorn,django。
注意:在Chrome上,它會顯示殘缺的圖像圖標。 瀏覽器上的源代碼顯示<img src="image.jpg/">
。 我注意到靜態文件的格式為: <img src="static/app1/image123.jpg
並顯示正常。也許我的問題圖像應該具有media / app1 / ...?
我的最終目標是使圖表/圖像令人失望,但是該圖像經常會通過更改從服務器上單獨應用程序的媒體文件夾中被覆蓋並進行更改。 這樣觀眾就可以得到最新的圖像。
簡化的文件結構,易於查看:
-website1
-media
image.jpeg
+static
-app1
-templates
-app1
index.html
layout.html
-website1
settings.py
..
website1 urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import include, url
from django.conf.urls.static import static
from website1 import settings
urlpatterns = [
path('admin/',admin.site.urls),
path('app1/',include('app1.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
app1的urls.py:
from django.conf.urls import url
from . import views
from django.urls import path, include
urlpatterns = [
path('', views.index,name='index'),
]
settings.py:
...
...
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT= 'media/'
views.py:
from django.shortcuts import render
from django.http import HttpResponse
import datetime
from PIL import Image
from django.core.files import File
from django.conf import settings
from io import BytesIO
import os
from app1.models import Item
def index(request):
now = datetime.datetime.now()
return render(request,'app1/index.html', {
'Data':now,
'itemContext':Item.objects.get(id=1)
})
index.html的:
{% extends 'app1/layout.html' %}
{% block content %}
<h1 align="center">{{Data}}</h1>
<h2 align="center">
{% load static %}
<img src="{% static "sentiment_analysis/image.jpeg" %}" alt="No immage"/>
</h2>
<h4>
{{itemContext.name}}
{{itemContext.description}}
<img src="{{ itemContext.image }}"/>
</h4>
{% endblock %}
app1的models.py:
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=32)
description = models.TextField()
image = models.ImageField(blank=True, null=True)
def __str__(self):
return self.name
nginx的/網站,avilable.conf:
...
...
root /usr/share/nginx/html;
index index.html index.htm;
location /static/ {
alias /home/jeff/website1/static/;
}
location /media/ {
alias /home/jeff/website1/media/;
}
...
...
[解決方案是文件權限問題...請參閱評論]
在圖像src中,您有雙雙引號,因此src無法正常工作,用它替換它,您應該會很好
<img src="{% static 'sentiment_analysis/image.jpeg' %}" alt="No immage"/>
eidt your code is like that
<img src="{% static " #this quotes ends here
sentiment_analysis/image.jpeg # this isnt inside any quotation
" %}" # second quotation start and end here
<img src="{{ itemContext.image }}"/>
<img src="{{ itemContext.image.url }}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.