Using static files in Django

shlokabhalgat

shlokabhalgat

Posted on March 4, 2022

Using static files in Django

Static files not loading in Django? The approach to making static files load on the browser and making sure it is correctly summoned in the HTML file is extremely precarious.

In this blog, I will explain why the static files are not loading as well as the necessary points to consider to call for them correctly-

Static files contain any media files-images, javascript, CSS, and likewise. Check step by step if the requirements are fulfilled properly-

  1. Make sure that django.contrib.staticfiles is included in INSTALLED_APPS in settings.py
  2. Check if you have defined STATIC_URL in settings.py as follows-
STATIC_URL = 'static/'
Enter fullscreen mode Exit fullscreen mode
  1. Check if your static files are in a folder called “static” in the root directory. Root directory is the project name directory where manage.py file is located.
  2. Adding static template path to the HTML file-
<html>
{% load static %}
    <body>
        <img src="{% static 'my_app/example.jpg' %}" alt="My image">
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Check if the STATICFILES_DIR is added below STATIC_URL in settings.py
STATICFILES_DIRS = [
    BASE_DIR / "static",
    '/<project_name>/<folder_name>/static/',
]
Enter fullscreen mode Exit fullscreen mode
  1. If none of the above steps work, add this path additionally to the STATICFILES_DIRS. So the final code will look something like this-
STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
Enter fullscreen mode Exit fullscreen mode

Additionally, please check the enclosures to add static files for css and javascript

  • <link rel="stylesheet" href="{% static 'css/style.css' %}">
  • <script src="{% static 'js/main.js' %}"></script>
💖 💪 🙅 🚩
shlokabhalgat
shlokabhalgat

Posted on March 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related