简体   繁体   中英

Image is not showing up on my website (django)

I am new to django. I wanted to upload an image but it doesn't show up on website. Instead, it shows a broken image icon. I tried to use load static block but it still doesn't work.

My html file:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Website</title>
</head>
<body>
   <h1>Hello</h1>
   {% load static %}
   <img src="{% static 'webdev/static/webdev/images/images.jpg' %}">
</body>

urls.py file:

from django.contrib import admin
from django.urls import path
from homepage import views

urlpatterns = [
    path('', views.home_page, name='home'),
    path('admin/', admin.site.urls),
]

views.py file:

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


def home_page(request, *args, **kwargs):
    return render(request, 'home.html', {})

file tree: https://i.stack.imgur.com/jtZ8t.png

The documentation on Serving static files during development explains how to set up static files. You need to add the views that serve the static files to the urlpatterns :

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

from homepage import views

urlpatterns = [
    path('', views.home_page, name='home'),
    path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

This will serve static files when DEBUG is set to True . In case of production ( DEBUG = False ), Django does not serve static files. Then you should configure the webserver (nginx/apache/…) to serve the static and media files, or work with a CDN.

Furthermore the path is:

<img src="{% static 'webdev/images/images.jpg' %}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM