Here is my main page, localhost:8000/helloworld/greeter at helloworld\templates\hello:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Hello!</title>
{% load static%}
<link rel="stylesheet" type = "text/css" href = "{% static 'hello/site.css' %}" />
</head>
<body>
<span class="message">Hello there, {{ name }}!</span> It's {{ date | date:'l, d F, Y' }} at {{ date | time:'H:i:s' }}.
</body>
</html>
and here is the CSS file at helloworld\static\hello (so it should look for localhost:8000\helloworld\static\hello\site.css):
.message{
font-weight
color: blue;
}
and here is the file structure:
The expected behaviour would be that the phrase "Hello there, [name]" is bolded and in blue, but here is what the code actually yields: (this is the problem)
And looking within the console gives this error:
GET http://localhost:8000/static/hello/site.css net::ERR_ABORTED 404 (Not Found)
Notice how it seems to think that "static" is at the root directory, when it is in localhost\helloworld.
I would like to find a solution to this problem and change it so that it links to the correct directory
I tried to change the block, specifically:
<link rel="stylesheet" type = "text/css" href = "{% static 'hello/site.css' %}" />
to:
<link rel="stylesheet" type = "text/css" href = "{% 'helloworld/static/hello/site.css' %}" />
I expect that it will apply the site.css but it didn't and threw a TemplateSyntaxError.
The problem is fixed like so:
In the file settings.py, I changed the line to become STATIC_URL = '/helloworld/static/'
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 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.
Here is my folder hierarchy:
/flask_app_2
run.py
/main
__init__.py
/static
/js
/styles
styles.css
/templates
html_page.html
I am trying to add styles.css to my html_page but I keep getting a 404 error.
<link rel="stylesheet" type = "text/css" href="/static/style/style.css">
Am I loading it correctly? Or do I possibly have a typo in my CSS file?
You're missing an "s" from your path.
<link rel="stylesheet" type = "text/css" href="/static/style/style.css">
Should be
<link rel="stylesheet" type = "text/css" href="/static/styles/style.css">
so "/static/styleS/style.css" instead of "/static/style/style.css".
It looks like you forget an "s" on styles
try this
<link rel="stylesheet" type = "text/css" href="/static/styles/styles.css">
I have my CSS in the following path: mysite/myapp/static/myapp/style.css. As of now, the CSS is simply:
body {
background-color: #F2B8F0
}
h1 {
color: #7BE0CB
}
I have my HTML set up like this: mysite/myapp/templates/myapp/home.html, where the following code is up on top:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
My settings.py is like:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
However, nothing happened, and the different text and background colors aren't showing up in my HTML. Does anyone happen to know why? Thanks!
Perhaps your css link tag is in the incorrect spot within your HTML. It should be as follows:
<!DOCTYPE html>
{% load static %}
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
</head>
<!-- YOUR HTML HERE -->
</html>
let
{% load static %}
be your first line in your HTML
Am working with django 1.3 and doing some template inheritance. My /static/ settings path seems to have problems once I leave the home page. Issue is, when I load home.html which inherits from base.html, the CSS and Image links work okay. But once I go to an extra URL (in this case vehicle.html), the css and image get lost with the error below:
console error
"GET /static/%20/static/images/logo_2.jpg HTTP/1.1" 404 1771
"GET /static/%20/static/css/default.css HTTP/1.1" 404 1765
view page source
<link rel="stylesheet" type="text/css" href="/static/ /static/css/default.css">
<link rel="stylesheet" type="text/css" href="/static/ /static/css/default.css">
It looks like some space is appearing from somewhere. Also, from the vehilce.html file, the page source shows that its adding an extra /static/ to the url plust the space. Where could I be going wrong? See below for my documents:
settings.py
STATIC_ROOT = 'D:/dev/workspace/vehicle_request/vehicle_request/mvmanager/static/'
STATIC_URL = '/static/'
urls.py
urlpatterns = patterns('',
url(r'^$', home_page),
(r'^admin/', include(admin.site.urls)),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), #Not in use in my code yet
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
(r'^vehicle/', vehicle),
(r'^driver/', driver),
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/static/css/default.css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<header>
<a href="http://localhost:8000" title="Home Page">
<img alt="logo2:" src="{{ STATIC_URL }}/static/images/logo_2.jpg"
style="float:left; margin:5px" height="100"; border=none"></a><br><br>
<h1>Vehicle Request System <span class="version">(Version 0.1 beta)</span></h1>
</header>
<hr style="clear: left">
<hr>
</body>
</html>
vehicle.html
{% extends "base.html" %}
{% block title %}Vehicle Registration{% endblock %}
{% block content %}
<html>
<head></head>
<body></body>
</html>
{% endblock %}
Thanks.
Edits
1. I've changed the stati in href="{{STATIC_URL}} /static/css/default.css"> to read static as that is how it is in my code. I must have backspaced by mistake while posting. Moving on however,
2. When I change {{STATIC_url}} /Static to {{STATIC_URL}}/Static ie. I remove the space between those two words -as suggested by #sarnold below-, home.html works as usual but vehicle.html still doesn't load the css and the image and it spews the error below in the console:
File "c:\Python27\lib\site-packages\django\core\files\storage.py", line 234, in path
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
SuspiciousOperation: Attempted access to '\static\images\logo_2.jpg' denied.
[10/Feb/2012 06:11:55] "GET /static//static/images/logo_2.jpg HTTP/1.1" 500 1731
File "c:\Python27\lib\site-packages\django\core\files\storage.py", line 234, in path
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
SuspiciousOperation: Attempted access to '\static\css\default.css' denied.
[10/Feb/2012 06:23:29] "GET /static//static/images/logo_2.jpg HTTP/1.1" 500 1731
3. When I combine #sarnold and #cptphil suggestions, vehicle.html loads perfectly the css and the image. home.html however fails. See the changes to base.html below:
base.html (edited to look like this)
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/default.css">
<img alt="logo2:" src="{{STATIC_URL}}images/logo_2.jpg"
home.html now doesnt' work! (viewing page source)
<link rel="stylesheet" type="text/css" href="css/default.css">
<img alt="logo2:" src="images/logo_2.jpg"
vehicle.html now works (viewing page source)
<link rel="stylesheet" type="text/css" href="/static/css/default.css">
<img alt="logo2:" src="/static/images/logo_2.jpg"
And this is how the home.html looks like in raw form
{% extends "base.html" %}
{% block title %}GEL: Vehicle Request System{% endblock %}
{% block content %}
{% endblock %}
I believe the template engine is doing what you are asking it to do.
href="{{STATIC_URL}} /stati/css/default.css"
correctly translates to
/static/ /stati/css/default.css
Try
href="{{STATIC_URL}}css/default.css"
in base.html if what you are after is
/static/css/default.css
Can't account for why home.html would work correctly though.
It looks to me like you added the spaces manually to base.html:
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}} /stati/css/defau...
<img alt="logo2:" src="{{ STATIC_URL }} /static/imag....
Take out the space before /stati/css and /static/imag and see if the problem goes away.
space = %20. Be sure to omit space from your url...
like : <script src="{% static " js/dashboard/salesPieChart.js" %}"></script>
To: <script src="{% static "js/dashboard/salesPieChart.js" %}"></script>