Manage Django Static Files (Images, JS, CSS)

June 12, 2020, 12:16 p.m.

Django Beginners · 6 min read

Manage Django Static Files (Images, JS, CSS)

If you are looking to add images to Django, you have come to the right place!

Django refers to images, JavaScript, and CSS files as static files or assets within your project. Follow the directions below to learn how to serve static files in development. All you really need is a static folder and a template to call the static template tag.

If you are looking to serve static files during production, follow the tutorial Serve Django Static and Media Files in Production

 

Create a folder for static files

env > mysite > (New Folder) static

Django static folder

In your Django project folder, create a new folder named static. This folder should be created in the project folder. In the example above, the static folder is in the project folder mysite.

 

Define the static URL in the settings

env > mysite > mysite > settings.py

# Application definition

INSTALLED_APPS = [
    'main.apps.MainConfig', 
    'django.contrib.staticfiles',
]

Now verify static files are listed under the installed apps in settings.py. It should already be listed as default. 

 

env > mysite > mysite > settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, "static"),
   ]

Then scroll down to the bottom of the settings file and define the static URL, if it is not present. You can also choose to add the static directory so your Django project knows which directories to look for your static files. 

With the basic configurations done, we will walk through how to add and display images in the templates along with connecting custom JavaScript and CSS files. 

 


 

Create a folder for image files

env > mysite > static > (New Folder) img

Django static img folder

Create a file within the static folder specifically for all of your images. You can choose to call it images or img, it does not make a difference, as long as you refer to the folder name correctly when referencing it later in your templates. 

 

Load static in the HTML template

env > mysite > main > templates > main > home.html

{% extends 'main/header.html' %}

  {% block content %}

  {% load static %}  #load static


   <div class="container">
  
   </div>


  {% endblock %}

Now go to the template of your choice, in this case, the home.html and load static at the top of the page. You must add {% load static %} to the top of the page before you call the image, of the image will not load correctly.

 

Use the static template tag

env > mysite > main > templates > main > home.html

{% extends 'main/header.html' %}

  {% block content %}

  {% load static %} 


   <div class="container">
     <img class="img-fluid" src="{% static "img/photo.png %}" alt="photo">
   </div>


  {% endblock %}

Then you can use the Django static template tag to serve the file using the URL. Note, that this file is using the Django extends tag and the Bootstrap CDN.

 


 

Create a folder for JavaScript files

env > mysite > static > (New Folder) js

Django static js folder

Now if you would like to add custom JavaScript files, create a new folder called js in static.

You could just use the <script> HTML element within your templates and place all of the functions within it, but creating a separate file can improve your project's overall file organization and keep all of the scripts in one easy-to-locate folder.

 

Create a script.js file

env > mysite > static > js > (New File) script.js

$(window).scroll(function() {
       if ($(document).scrollTop() > 600 && $("#myModal").attr("displayed") === "false") {
         $('#myModal').modal('show');
         $("#myModal").attr("displayed", "true");
       }
     });

You can then create a script.js file that holds your JavaScript functions.

 

Load the JS script in the HTML template

env > mysite > main > templates > main > header.html

<!DOCTYPE html>
<html>
  <head>
    {% load static %}
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <!--Bootstrap CSS-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  </head>
  <body>

    {% block content %}

    {% endblock %}

    <!--Custom JS-->
    <script src="{% static 'js/script.js' %}"></script>
  </body>
</html>

Now, to actually connect your JavaScript file to the rest of your project, add an HTML script element to the header.html file. The script file is called using the same static tags as the images. Note, that you do need to {% load static %} at the top of the page.

You may also notice that the file is using block content and the BootstrapCDN.

 


 

Create a folder for CSS files

env > mysite > static > (New Folder) css

Django static css folder

You can choose to do the same thing for CSS files. Create a new folder called css in the static folder.

Again, you could use the <style> HTML element in your templates and nest all of the CSS declarations within it. But if you are making custom class attributes that apply to elements within multiple templates, this is a good D.R.Y. coding solution. 

 

Create a stylesheet.css file

env > mysite > static > css > (New File) stylesheet.css

.custom {
   color:#007bff;
   background:#ffffff;
   font-size:20px;
}

You can then create a stylesheet.css file that holds all of your CSS declarations in one location.

 

Load the CSS link in the HTML template

env > mysite > main > templates > main > header.html

<!DOCTYPE html>
<html>
  <head>
    {% load static %}
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <!--Bootstrap CSS-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <!--Custom CSS-->
    <link rel="stylesheet" href="{% static 'css/stylesheet.css'%}" type="text/css">

  </head>
  <body>

    {% block content %}

    {% endblock %}

    <!--Custom JS-->
    <script src="{% static 'js/script.js' %}"></script>
  </body>
</html>

Now, to connect your custom stylesheet to the rest of your project, add an HTML link element to the header.html file. The linked CSS file is called using the same static tags used for the images and JavaScript files. Again, please note that you do need to {% load static %} at the top of the page. You will get an error if you forget to add it. 

 


 

Solving errors related to Django load static

If you get the error Invalid block tag on line 8: 'static', expected 'endblock'. Did you forget to register or load this tag?:

You probably forgot to load the static tag at the top of the file. The solution is to add {% load static %} to the file, before you call the image.

{% load static %}

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

 

If you get the error Could not parse the remainder: '/photo.jpg' from 'img/photo.jpg':

Check to make sure that you added quotation marks around the URL of the image. There are two sets of quotations that need to call the static asset. Just be sure not to include the static tag.

<img src="{% static img/photo.jpg %}"> #wrong format

<img src="{% static 'img/photo.jpg' %}"> #correct format

 

If you are getting the error Invalid block tag on line 9: ''static/img/photo.jpg'', expected 'endblock'. Did you forget to register or load this tag?:

You may have accidentally added the static tag to the URL.

<img src="{% 'static/img/photo.jpg' %}"> #wrong format

<img src="{% static 'img/photo.jpg' %}"> #correct format

 

If your page isn't loading and the CLI states django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the required STATIC_URL setting:

Then you forgot to add the static URL to the settings file. Add the static URL to the settings.py file then save the document. 

STATIC_URL = '/static/'

 

Finally, if you are not getting a Django error page, but have a broken image icon, you need to make sure you are formatting the URL correctly with the Django template tag format.

<img src="{ static img/photo.jpg }"> #wrong format

<img src="{% static 'img/photo.jpg' %}"> #correct format

0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments