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-
- Make sure that django.contrib.staticfiles is included in INSTALLED_APPS in settings.py
- Check if you have defined STATIC_URL in settings.py as follows-
STATIC_URL = 'static/'
- 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.
- Adding static template path to the HTML file-
<html>
{% load static %}
<body>
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
</body>
</html>
- Check if the STATICFILES_DIR is added below STATIC_URL in settings.py
STATICFILES_DIRS = [
BASE_DIR / "static",
'/<project_name>/<folder_name>/static/',
]
- 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"),
)
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>
Top comments (0)