django2 + python3 顯示靜態文件中的圖片


之前一直搞不出來 是因為圖片的問題,步驟也就是固定的幾步,到位了就差不多成了

文件夾結構:

. ├── HelloWorld │   ├──
__init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-36.pyc │   │   ├── settings.cpython-36.pyc │   │   ├── urls.cpython-36.pyc │   │   └── wsgi.cpython-36.pyc │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── db.sqlite3 ├── hello │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-36.pyc │   │   ├── admin.cpython-36.pyc │   │   ├── models.cpython-36.pyc │   │   └── views.cpython-36.pyc │   ├── admin.py │   ├── apps.py │   ├── migrations │   │   ├── __init__.py │   │   └── __pycache__ │   │   └── __init__.cpython-36.pyc │   ├── models.py │   ├── static │   │   └── hello │   │   └── 6.png │   ├── templates │   │   └── index.html │   ├── tests.py │   └── views.py └── manage.py

settings.py文件加這兩句

STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/')

views.py文件加

from django.shortcuts import render

from django.shortcuts import render
from django.http import HttpResponse

def showImg(request):
    return render(request,'index.html')

urls.py

from django.contrib import admin
from django.urls import path
from hello import views
from django.conf.urls.static import static
from . import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.showImg)
]

index.html文件

一定要寫

{% load staticfiles %} 這句
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    {% load staticfiles %}
</head>


<body>
<h1>顯示一張本地圖片</h1>
<img src="{% static '6.png' %}" width="500" height="500" alt="圖片無法顯示">
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM