skip to Main Content

Kindly help, my django can’t link my css to my html template.I’ve implemented almost every solution i could find, added some recommended url patterns, tried full paths instead of relative, ensured i had things set up correctly from the official docs, but can’t find what I’m missing.

My settings:

STATIC_URL = '/static/'

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

file path: BASE_DIR/static/css/main.css

store.html:

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

<h3>Store</h3>

errors:
GET http://127.0.0.1:8000/static/css/main.css net::ERR_ABORTED 404 (Not Found),
GET /static/css/main.css HTTP/1.1" 404

2

Answers


  1. Consider using this format to use static in your django template:

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

    If this doesn’t work:
    In your Django project’s urls.py file, make sure you have configured the static view to serve static files during development. Add the following import at the top of your urls.py:

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

    If still does not work then either
    Try placing the static folder into templates folder/app folder.

    or

    RECOMMENDED Try printing BASE_DIR variable now check if your static folder exists in the BASE_DIR path.

    Login or Signup to reply.
  2. you should also define static root in settings.py:

    STATIC_ROOT = BASE_DIR / 'staticfiles'
    

    and in urls like what Proud Wadhwa said write this:

    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search