djangodjango-staticfiles

Django is not rendering my static file (css, images, etc)


I am able to view my site (html)in the browser but none of my mark-up is working. I have checked my stylesheet links for types, settings.py, but I am at a lost.
When I run my site I am getting the below responses in my terminal.

[10/Nov/2022 20:46:23] "GET / HTTP/1.1" 200 168
[10/Nov/2022 20:46:23] "GET /static/css/main.css HTTP/1.1" 404 1795
[10/Nov/2022 20:46:23] "GET /static/images/6%2Bcart.png HTTP/1.1" 404 1810`

Here is code from my settings.py file:

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

Example of my css link in my html page

{% load static %}

<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">

I have tried going over everything possible but cannot locate the issue, any and all feedback would be greatly appreciated. I am not allowed to post images yet so unfortunately, I could not include.

I have re-coded, deleted and remade static folder, scoured the internet with no luck yet.


Solution

  • Try this static file configuration, this is work well for me.

    In settings.py:

    STATIC_URL = 'static/'
    STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/')]
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # for deployment
    

    And add in urls.py:

    from django.conf.urls.static import static
    from django.conf import settings
    
    urlpatterns = [
    
        """
        -----
        -----
        """
     ]
    
    
    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL , document_root = settings.STATIC_ROOT)
    

    If it still doesn't work, you can add below code in your urlpatterns to force django to serve static files.

    from django.urls import path, include, re_path
    from django.views.static import serve
    
    urlpatterns = [
        re_path(r'^static/(?P<path>.*)$', serve, {'document_root':settings.STATIC_ROOT}),
    ]