Django图像未在模板中显示

xmjla07d  于 2022-11-18  发布在  Go
关注(0)|答案(3)|浏览(148)

我花了一整天的时间试图找到一个解决方案来显示模板中的图像,但我找不到任何解决方案来解决我的问题。
这是我的设置

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_DIRS = [
 os.path.join(BASE_DIR, 'DataCallGuide/static')
]

我的模型

class TroubleshootingSteps(models.Model):

    box_header = models.CharField(blank=True, null=True, max_length=250)
    box_content = models.CharField(blank=True, null=True, max_length=250)
    box_botton = models.CharField(blank=True, null=True, max_length=250)

    header = models.TextField(blank=True, null=True)
    sub_header = models.TextField(blank=True, null=True)
    text1 = models.TextField(blank=True, null=True)
    image1 = models.ImageField(blank=True, null=True, upload_to="images/")

并且所述模板

{% extends 'base.html' %}
{% load static %}
{% block content %}

 <div class="container overflow-hidden">
  <div class="text-center">
   <h4 class="mt-5 mb-5">{{data.header}}</h4>
  </div>

  <h3 dir="rtl" class="rtlss">{{data.sub_header}}</h3>
  <img src="{{ data.image1.url }}">

  </div>

{% endblock%}

此外,当我点击管理页面中的图像链接时,它不会显示图像,显示页面未找到错误,下面的链接http://127.0.0.1:8000/media/images/IMG-20220901-WA0009.jpg有什么问题吗?

km0tfn4u

km0tfn4u1#

如果图像未从静态文件夹加载,则执行此操作

# do comment static root path

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# add static dirs path like this

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

#----------- OR ---------------

STATICFILES_DIRS = [BASE_DIR / 'static']

如果图像未从媒体文件夹加载,则执行此操作

# --------- Show Image in Html   ---------

# Add Code in Project (urls.py)
from django.contrib import admin
from django.urls import path,include

from django.conf import settings # --------> this
from django.conf.urls.static import static # --------> this

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # --------> this

# Add Code in Project (setting.py)
# MEDIA_ROOT =  os.path.join(BASE_DIR, 'media') 
MEDIA_ROOT =  BASE_DIR / 'media' 
MEDIA_URL = '/media/'
sxissh06

sxissh062#

您是否修改了您的url.py?

urlpatterns = [
    Your urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
zujrkrfu

zujrkrfu3#

而不是:

<img src="{{ data.image1.url }}">

试试这个办法:

<img src="/media/{{ data.image1 }}">

相关问题