pythondjango-staticfilesdjango-3.1

Static images are not loading in django 3.1.7


I'm trying to display images in my web app but for some reason, it is not showing and giving a 404 error. I think in urls.py I added static correctly and even if change it to STATIC_ROOT still no sense. At the same time IDE not giving any error simply static not working.

settings.py



from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
 'blog.apps.BlogConfig',
 'jobs.apps.JobsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'portfolio',
]

# Skipped Database and some other parts.

# STATICFILES_DIRS = [
#     os.path.join(BASE_DIR, 'static')
# ] That part is giving error in new django 3.1.7 so I removed.

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

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

***urls.py***                     

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
import jobs.views

urlpatterns = [
 path('admin/', admin.site.urls),
 path('', jobs.views.home, name='home'),
 path('blog/', include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

**home.html**
<img src="{% static 'images/img1.JPG' %}" alt="Couldn't load" class="img-fluid" height=150 width=150>
#this is specific part of the html 

Solution

  • Django 3.1.7 uses this syntax: Build paths inside the project like this: BASE_DIR / 'subdir'.

    In place of subdir, you should write static