Django static files 404 error

Elgin Cahangirov picture Elgin Cahangirov · Dec 10, 2017 · Viewed 9.6k times · Source

I'm trying to locate all bootstrap files in django project in only one folder and reference them. In order to do that I've added these lines to setting.py:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

My base.html looks like this:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Muplay</title>
    <link rel="stylesheet" type="text/css" href="{% static'css/bootstrap.css' %}">
    <script src="{% static 'js/bootstrap.js' %}"></script>
</head>
<body style="background-color: #F2F2F5">
    {% include 'snippets/nav.html' %}
    <div class="container">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

When I extend this base.html to other html files css and js file is loaded successfully in browser. But, problem is that, in terminal, django returns 404 error as follows:

[10/Dec/2017 14:03:27] "GET /static/js/bootstrap.js HTTP/1.1" 404 1759
[10/Dec/2017 14:03:27] "GET /static/css/bootstrap.css HTTP/1.1" 404 1765

Why django returns 404 code while those static files are successfully loaded in browser?

Answer

Anusha Prasanth picture Anusha Prasanth · Dec 10, 2017

Remove STATIC_ROOT Add STATICFILES_DIRS to the settings file.(Recommended during development)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATICFILES_DIRS :

This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.

This should be set to a list of strings that contain full paths to your additional files directory

STATIC_ROOT :

The absolute path to the directory where collectstatic will collect static files for deployment.

If you want to use STATIC_ROOT, then run the command python manage.py collectstatic which will collect all the static files to the static directory mentioned in STATIC_ROOT. This is used during deployment.

Find the detailed documentation here.