0

I want to add a static file to my django project app.

My app is named "core"

Hence inside the app where I need the static file (called main.css) , I made a directory named static/core/main.css

So after that my directory looks like this

core
....
-static
|_core
  |_main.css
.........

And in the settings.py file , I wrote this

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

And in the html file where I want the static css I wrote this

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %} Welcome | Ecommerce {% endblock %}</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
    <link rel="stylesheet" href="{% static 'core/main.css' %}">

This HTML file is located in a global project level template folder where I dump the templates from all the apps in the project .

But my static file is not getting loaded for some reason

2 Answers2

0

May be because you didn't specify the file?

I guess you should change it from

<link rel="stylesheet" href="{% static '' %}">

To

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

Try to add

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

into your Django settings

evermake
  • 30
  • 1
  • 4
  • Sorry . I had mentioned the file name in my original code but I did not copy paste it correctly . <-- this is what i have in my code too. It is still not working –  Apr 19 '21 at 08:38
  • Does Django shows any errors? Are you sure that BASE_DIR found correctly in your project? Are static files loaded on other pages? Did you try to restart the server? – evermake Apr 19 '21 at 08:41
  • You can try to manually go to the address /static/core/main.css? Is the server responding with a 404 error? – evermake Apr 19 '21 at 08:44
  • <-- When I wrote this line in pycharm , I am getting a warning "Unresolved template reference ''core/main.css'' " –  Apr 19 '21 at 08:47
  • Probably you need to add your static directory to STATICFILES_DIRS setting as Nguyễn Vũ Thiên mentioned. See more https://docs.djangoproject.com/en/3.2/ref/settings/#staticfiles-dirs – evermake Apr 19 '21 at 08:52
-1

In Your settings.py file add this

STATIC_URL = '/static/'
if DEBUG:
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static')
    ]
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

after that open the terminal in your root directory and run the following command

python manage.py collectstatic

you can also refer to the django documentation where they have explained about staticfiles in django https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/