Search code examples
pythondjangowebdjango-staticfiles

404 Static file not found - Django


I have an issue with django. I recently bought an instance of a shared server and I wanted to move my django website from AWS to this server (which use Cpanel). All worked fine with AWS but when I switched to Cpanel all statics files were missing.

this is my settings.py:

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

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"

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

my project structure:

my_project
|-app/
    |-...
    |-views.py
|-db.sqlite3
|-manage.py
|-media/
|-my_project/
    |-...
    |-settings.py
|-static/
    |-main_page/
        |-js/
            |-my-script.js

I add static files like this:

{% load static %}
<script src="{% static 'main_page/js/my-script.js' %}"></script>

This is the error:

GET http://my.domain.com/static/main_page/js/my-script.js net::ERR_ABORTED 404 (Not Found)

When I go to the URL of the file it understands it like one of my URLs:

404 error screenshot

I hope you will help me to solve this issue ;) thanks.


Solution

  • you need to add the static & media files config in the urls.py , like this

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] 
    urlpatterns  +=  static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    the django docs : https://docs.djangoproject.com/en/3.1/howto/static-files/