DarkFire67
DarkFire67

Reputation: 13

linking css stylesheet django python3?

I am pretty new to Django and I do not know how to link CSS and or javascript to my project. Don't want to have a project with no CSS. Thank you for any help, sorry if this is a very dumb question. Have a nice day!

Upvotes: 1

Views: 66

Answers (1)

MaisyDoge13
MaisyDoge13

Reputation: 154

you problem is that you need to link static files from your html template. this is fairly easy in django, just create a folder called staticfiles in the root directory and create a folder called css inside of it. Put your styles in there. go to your settings.py and change

STATIC_URL = whatever
STATIC_ROOT = whatever

to

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_DIR = [
    os.path.join(BASE_DIR, "staticfiles")
]

you see, in django settings, you can't have the static root be the same as what folder you are using for static files in production. for your urls.py in the folder inside the base directory named after your project add this after urlpatterns

from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += (static(settings.STATIC_URL, document_root= os.path.join(settings.BASE_DIR, "staticfiles")))

now in your base template put

{% load static %}

before the html tag and

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

in the head tag. I hope this has helped!

Upvotes: 2

Related Questions