Load Static files and Media Files in Django

Static Files such as Images, CSS or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server.

Open settings.py file in your Django project and set STATIC_URL and STATICFILES_DIRS variables.

We need to load the static files by adding the below line of code in HTML file.

{% load static %}

Then, insert the stylesheet in the HTML using link HTML tag.

<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>

<img src = "{% static 'image.png' %}" height="200" width="200" >

Adding Media Files:

Open urls.py file in your Django project and set urlpatterns :

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

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

Sign In or Register to comment.