Django - Add Static Files



What are Static Files in Django?

The django template language allows data to be inserted in a web page dynamically. However, a web application also needs certain resources such as images, JavaScript code and style sheets to render the complete web page. These types of files are called static files. In a Django application, these files are stored in a static folder inside the application folder.

The Staticfiles App

The staticfiles app (django.contrib.staticfiles), which manages the static files, is installed automatically in a Django project.

INSTALLED_APPS = [
   . . .,
   'django.contrib.staticfiles',
   'firstapp',
]

Django looks for all the static assets in the "app/static" folder (a folder named as static in the app’s package folder).

First, we need to create a folder named "static" inside the myapp package folder to store these files. Let us store the "django.png" file in this folder.

Make sure that in the "settings.py" module, the STATIC_URL parameter is set to point to this folder.

STATIC_URL = 'static/'

Add a View

Let us add the following view −

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

# Create your views here.
def index(request):
   return render(request, "index.html", {})

Register the View

You should also register this view in the app's URLCONF −

from django.urls import path
from . import views

urlpatterns = [
   path("", views.index, name="index"),
]

In the template, to make the static folder available, use the load template tag as in the following statement −

{% load static %}

index.html

Now, we can use the static path to refer to the image in the <img src> tag. Let us modify the "index.html" file as −

<html>
<body>
   {% load static %}
   <img src="{% static 'django.png' %}" alt="My image">
</body>
</html>

Start the server and visit the URL "http://localhost:8000/myapp/". The "django.png" file will be displayed in the browser.

Django Add Static Files

The staticfiles app also helps in serving the CSS and JS files. To include it as a CSS file, provide its relative path to the {% static %} tag in the href attribute.

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

To load the JavaScript code, use the following syntax −

<head>
   {% load static %}
   <script src = "{% static 'script.js' %}"></script>
</head>
Advertisements