I am using a CSS file to update my HTML in a Django app, but despite the fact that my "style.css" sheet is linked to the HTML file, there are no updates occuring.
"style.css" is in the same folder as my HTML document ("index.html"), but nothing is changing.
I've pasted my code below:
<head>
<link type="text/css" rel="stylesheet" href="style.css" media="screen"/>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
I know that the CSS and HTML files are linked, because when I hover over the "style.css"href, I can press CTRL + click, and "styles.css" opens in a new window.
I've been through four or five tutorials, tried to restarted the local server, moving "style.css" to its own folder "styles", and then changed href to href="styles/style.css" but it is still not working.
I'm using VSCode, and Windows 11.
you need config template section in django settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
be carefull to create static and templates directory in project root or any
place you want and set in "DIR" in TEMPLATES for templates and set static for static files for js and css file. in static directory you must put your js and css file also you can create directory inside static directory called "js" hold js files and create "css" directory inside static for css files.
now render yout html file in view like below
from django.shortcuts import render
def index_view(request):
return render(request, "index.html")
now in your template files you can load static files
<!DOCTYPE html>
<head>
{% load static %}
<script src="{% static 'app.js' %}"></script>
<title>Site</title>
</head>
<body>
<img src="{% static 'img.png' %}" alt="Mon image" />
{% block content %}{% endblock %}
</body>
</html>
in your html file you should add:
{% load static %}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link type="text/css" rel="stylesheet" media="screen" href="{% static 'styles/style.css' %}"/>
<title>Document</title>
</head>
you should add in your setting.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
also you should declare your folder structure like this:
in your root project (where manage.py declared), static folder and in your static folder you should have styles and in your styles is your style.css file.
static/styles/style.css
Apparently it was just a cache issue. Clearing it took care of this, so I'm now clearing the cache every time I modify anything in the CSS Templates, which comes to clearing the cache basically everyday.
Related
How do I create a div for each directory using flask?
I tried this but it does not do anything and theres nothing in the console:
python file:
# Get a list of directories in the 'servers' directory
folders = [d for d in os.listdir('servers/') if os.path.isdir(d)]
# Create a div element for each folder
divs = []
for folder in folders:
div = f"<div class='list'><a href='/servers/{folder}'>{folder}</a></div>"
divs.append(div)
# Join the div elements into a single string
divs_string = "\n".join(divs)
# Render the template and pass the div elements as a variable
return render_template('home.html')
html file (home.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/home.css') }}" />
<link rel="stylesheet" href="https://rawcdn.githack.com/CrystalVortex/Feather-CSS/9318334ceedfa61d6a64349a558ef1e48ef19cb2/Feather1.7.css">
<title>FeatherPanel | Home</title>
</head>
<body>
<form action="/create" method="post">
<button class="btn_blue">Create Server</button>
</form>
{% for directory in directories %}
<div>{{ directory }}</div>
{% endfor %}
</body>
</html>
The listdir function just returns a list of filenames. To test within your loop whether it is a directory, the isdir function expects the path including the folder name.
You can then pass the returned list to the template.
I'm using locals() here to pass all local variables to the template. However, you can also pass the variables individually with a key.
#app.route('/servers/')
def servers():
# Get a list of directories in the 'servers' directory
folders = [d for d in os.listdir('servers') if os.path.isdir(os.path.join('servers', d))]
# Render the template and pass the div elements as a variable
return render_template('home.html', **locals())
Within the template you can iterate over said list to create a "div" element for each entry.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/home.css') }}" />
<link rel="stylesheet" href="https://rawcdn.githack.com/CrystalVortex/Feather-CSS/9318334ceedfa61d6a64349a558ef1e48ef19cb2/Feather1.7.css">
<title>FeatherPanel | Home</title>
</head>
<body>
<form action="/create" method="post">
<button class="btn_blue">Create Server</button>
</form>
{% for folder in folders %}
<div>{{ folder }}</div>
{% endfor %}
</body>
</html>
You didn't describe what should happen when a user clicks a link for a listed directory. Keep in mind that only files in the static folder are accessible from the client. If you want to use an anchor to refer to listed directories outside of the static folder, you need another endpoint.
I know there are so many questions on this but I'm yet to find a solution. I have the below folder structure for my django app:
I then reference the styles.css file from my index.html page, like so:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
{% load static%}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
but no matter what I change in my css file it doesn't affect my webpage.
css file if useful:
.form-details {
text-align: center;
color: Tomato;
background-color: red;}
Place {% load static %} line to the top of your index.html file.
And also be sure that you correctly set static files direction in the settings.py file.
For example,
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static_assets'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
UPDATE: This solved. I didn't write the correct CSS!
I am trying to render a few things in HTML. Multiple things are causing problems but I've included the most basic part I want to get working. If I can get this to work, I can get the rest to work.
Very simple app structure:
app
api.py
static
styles.css
templates
index.html
This is the contents of index.html:
<html>
<h1>
Title here
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</h1>
</html>
This the the CSS I'm using:
h1 {
color: red
text-align: center
}
Relevant code in api.py:
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
#app.get("/", response_class=HTMLResponse)
def read_mean_cpu(request: Request, device_id):
return templates.TemplateResponse("index.html", {"request": request}))
Any idea why the CSS isn't taking?
i'm trying to deploy my react app through firebase but after deploying i get a blank page and the SyntaxError: expected expression, got '<'. i think this is because it's reading the < from html but i'm not sure how to solve this. below is the index.html form my build folder which is initialized as the source for firebase
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link href="../src/App.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Merriweather:900" rel="stylesheet">
<link rel="manifest" href="/CV/manifest.json">
<link rel="shortcut icon" href="/CV/favicon.ico">
<title>Lorenzo Wijtman</title>
<link href="/CV/static/css/main.1b15713e.css" rel="stylesheet">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="/CV/static/js/main.1b785adb.js"></script>
</body>
</html>
my firebase.json content below
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
Your HTML contains this script include:
<script type="text/javascript" src="/CV/static/js/main.30b4dcd1.js"></script>
If you try to load this URL, you will see that you're getting back your original HTML, instead of a JavaScript file. Since you told the browser to expect JavaScript, it is complaining about the angular brackets.
It looks like you're not deploying a /CV/static/js/main.30b4dcd1.js. Since you're telling Firebase Hosting to rewrite everything to /index.html, that's what it does when there is no matching file for a URL.
This is a bit embarrassing, but I don't know how to solve this problem:
First off, my project directory looks like this (there are more directories, but we aren't concerned with them):
projectfolder/
wsgi/
openshift/
templates/
home/
simple-sidebar.html
static/
css/
fonts/
js/
And the file we are concerned with is simple-sidebar.html which looks like the following :
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href= "{% static "css/bootstrap.css" %}" rel="stylesheet">
<!-- Add custom CSS here -->
<link href="{% static "css/simple-sidebar.css" %}" rel="stylesheet">
<link href="{% static "font-awesome/css/font-awesome.min.css" %}" rel="stylesheet">
</head>
Now for some reason my static template tags are not working, but that's probably because I don't know how to set up my static template stuff in my settings.py:
STATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = () <--- dont know if I need this one?
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
PS: Also how would you do this without the {% static %} tag? I am not sure how my style sheets href would look like.
Try removing the dots from your STATIC_ROOT, for example
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATICFILES_DIRS are there for you if you'd like to map additional folders to your application that can be anywhere on your machine. When you run ./manage.py collectstatic you're essentially asking python to find all the files within said directories and drop them into the static folder defined in STATIC_ROOT
If you would like to map your files manually (without the static tag) you'd have to write out the full path of your file, for example /some/directory/path/css/style.css.
Lastly if you're running with DEBUG = True you are required to add your static and media urls to urls.py so there is an actual path in place. For example
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT}))