Part 4 - Static and Media Files


django.png

 

Create:

mysite/
    static/
        img/
            
django.png

 


 

Defining paths and URLs

STATICFILES_DIRS = [
	BASE_DIR / 'static',
]

STATIC_ROOT = BASE_DIR / 'staticfiles'

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

STATIC_URL → public URL for static files
STATICFILES_DIRS → source folders for static files (development)
STATIC_ROOT → final directory after collectstatic (production)
MEDIA_ROOT → where user uploads are stored
MEDIA_URL → public URL for media files

 

Mapping

from django.conf import settings
from django.conf.urls.static import static

...

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

static() maps web URLs with actual static or media files.


Templates

{% load static %}
<h1>Hello World!</h1>
<img src="{% static 'img/django.png' %}">

 


Access through the browser:
http://localhost:8000


Tested with Django 5.2



12 Feb. 2024 | Last Updated: 02 Jan. 2026 | jaimedcsilva

Related
  • Part 1 - Virtual Environment
  • Part 2 - Setting up a Django Project
  • Part 3 - Templates, Views and URLs
  • Part 4 - Static and Media Files
  • Part 5 - Models and Database
  • Part 6 - Connecting everything
  • Part 7 - Publishing to the internet

  • Buy Me a Coffee