This is probably a stupid question. I'm new to Django and I was wondering how to use CSS when it is in a different file.
Right now, my file paths looks like this:
CSS: web/static/web/style.css
HTML: web/templates/web
My HTML file looks like this:
{% load static %}
<!--HTML-->
<body>
<div >
<a href="/">Home</a>
<a href="/donate">Donate</a>
</div>
</body>
My CSS looks like this:
.topnav {
background-color: #333;
overflow: hidden;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #04AA6D;
color: white;
}
How can I get the HTML to use the CSS from a different file?
CodePudding user response:
add a <head>…</head>
tag and type <link rel="stylesheet" href="static/web/style.css"/>
inside the <head>…</head>
tag.
Make sure the <head>…</head>
is outside the <body>…</body>
tag. Here is the new code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="static/web/style.css"/>
<!--other head contents like title and meta tag goes here-->
</head>
<!--HTML-->
<body>
<div >
<a href="/">Home</a>
<a href="/donate">Donate</a>
</div>
</body>
</html>
CodePudding user response:
This method works for me.
Create a directory called staticfiles then inside that folder create a css directory.
Then check the settings.py file to make it look like this:
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
Then go to the main urls.py file of the project and add this:
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = staticfiles_urlpatterns()
And then in the html file, add this one and it should work now:
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">