Why won't my Flask app connect to my CSS files? [duplicate] - python

This question already has answers here:
CSS file not refreshing in browser
(15 answers)
Closed 5 years ago.
Here is my project hierarchy:
Project
Here is my HTML file :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='custom.css') }}"/>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
My .py flask file :
from flask import Flask, render_template, redirect, json, url_for, request, abort
from pymongo import MongoClient
client = MongoClient()
db = client.web_zoo
app = Flask(__name__)
#app.route('/')
def index():
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
And my CSS file :
body {
color: green;
}
h1 {
color: orange;
}
The HTML and .py files work fine and the HTML is rendered and displayed on the page. However the CSS doesn't change. It just displays it in normal black text.
NOTE : All those imports are there as I was doing something else. I stripped off everything else and still have this problem.
I can link bootstrap to it, and the CSS works, but not for my own CSS files.
I have looked at and tried these following solutions :
CSS Problems with Flask Web App
Application not picking up .css file (flask/python)
best way to override bootstrap css
It's probably quite obvious but I'm stuck. Any help? Thanks in advance!
EDIT - I have added a picture of the project hierarchy now instead of just a list. As you can see there are some other HTML files in there too, but none are used nor referenced.

Try
CTRL+SHIFT+R
in Chrome to reload the CSS.
On Mac try:
CMD+SHIFT+R
Otherwise right-click on the page in Chrome, select Inspect and select the Console tab to see what errors you get.

Related

HTML file cannot load CSS file, browser says net::ERR_ABORTED 404 even though in the same directory [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 2 years ago.
I'm trying to create a simple flask app, and I'm new to HTML and CSS. I can't seem to link my CSS file to my HTML file and have it load successfully on my webpage. I've looked at other threads to no avail, and most of the comments centre around file structure, which seems fine to me, so I have no idea what the issue is. Both my html file and CSS file are in the same directory, and in my HTML file I have
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h1>Welcome</h1>
</body>
</html>>
My CSS file is indeed called styles.css and just contains
h1 {
color: blue;
text-align:center
}
I've tried about a dozen other combinations for href and none seem to work.
Here is a screenshot of my file structure from Github
The two HTML and CSS files are in the "templates" directory.
No matter how I change the file structure, I get the error:
GET http://127.0.0.1:5000/styles.css net::ERR_ABORTED 404 (NOT FOUND)
when I inspect the page http://127.0.0.1:5000/
Not sure if I'm making some really trivial error, but any help at all would be greatly appreciated.
Thanks
In case both of files are in the same directory, you cannot locate CSS-file as you did ./styles.css. Try this one:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome</h1>
</body>
</html>

flask reading text file and view it in html page as lines [duplicate]

This question already has answers here:
Jinja render text in HTML preserving line breaks
(3 answers)
Closed 3 years ago.
my python code
from flask import Flask,render_template,request
import os,glob
f=open('filename.txt','r')
g= f.read()
app= Flask(__name__)
#app.route('/')
def index():
return render_template('index.html',n=g)
if __name__=="__main__":
app.run(debug=True)
and this is my html code
<html>
<head>
<title>admin</title>
</head>
<body>
<p>{{n}}</p>
</body>
</html>
it's shows me the output as one single line but I want it to show the lines Below each other.
This is more of an HTML problem.
You'll need to introduce HTML line breaks (<br>) in the rendering of the object.
Try replacing \n in your file w/ <br> (e.g., g = g.replace('\n', '<br>')).
(Or you can insert breaks programatically)
Also, in your HTML, change {{ n }} to {{ n|safe }}.
You may want to read more on Jinja formatting here: https://jinja.palletsprojects.com/en/2.10.x/templates/
What you are looking for is an HTML tag called pre
Try this :
<html>
<head>
<title>admin</title>
</head>
<body>
<div>
<pre>{{n}}</pre>
</div>
</body>
</html>
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
You should have more information in this question:
where are you viewing this output? in a terminal, in the browser after running flask's wsgi app?
are you trying to view the raw html text or formatted html like a web browser?
what version of Flask are you using?

Error 404 - Getting Stylesheet Working in Bottle (Python Webframework)

I'm using bottle (the python webframework) to familiarize myself with html, js and css and using localhost to access the site. I can't quite get the css file to be applied to the site that the templates link to. Sometimes it works, but when I edit the file, it doesn't update and even loses the file and can't find it, even after restarting the server. The Console gives the 404 error (file not found), even though I have not moved it.
I first noticed the issue when the CSS wouldn't update in the browser when I refreshed. After clearing out the cache every time I edited, I found the 404 not found issue. I've validated the css file to check if a synthax error was the issue. It came back clean. I redownloaded the bottle.py file in case it needed an update. Still the same result. I also triple checked the link path, even tried to put them all into the same folder with no change.
Here is my file structure:
project folder
static
css
main.css
views
home.tpl
bottle.py
server.py
start.bat (starts the server)
Here is the code in server.py
from bottle import route, run, template
#route('/')
def home():
return template('home')
run(host='localhost', port=8080, debug='True', reloader='True')
Here is the template home.tpl:
<!DOCTYPE html>
<html>
<head>
<title>Bottle Site</title>
<link rel="stylesheet" type="text/css" href="/static/css/main.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Header!</h1>
</div>
<div id="navigation">
<ul>
<li>Home</li>
</ul>
</div>
<div id="section">
Section text!
</div>
<div id="footer">
© 2019 - <b href="#" id="dev">Footer/b>
</div>
</div>
</body>
</html>
I'd like to reliably be able to apply the css to the site without it crashing and sometimes not finding the file. Whenever I paste a fresh copy of my css file and start the server, it works fine until I try and change the file (a background color, for example. Nothing syntax breaking) but it doesn't update. when I clear the cache, it turns into a plane html file and the console reads:
"GET /static/css/main.css HTTP/1.1" 404 764
I just figured it out.
In the server.py file, you apparently need a:
#route('/static/<filename:path>')
def send_static(filename):
return static_file(filename, root='./static/')
to give the server a route that it can access and find the files (i think).
So in the templates, to show it where they are, you can say:
<link rel="stylesheet" type="text/css" href="/static/css/main.css" />
And it will work fabulously every time. :)
Why without the route it sometimes found the file and sometimes not will forever be a mystery of computer science.
Routes are hard.
Have a nice day! :)
I also like to use whitenoise with bottle.
from whitenoise import WhiteNoise
...
botapp = WhiteNoise(botapp)
botapp.add_files(staticfolder, prefix='static/')

Upload images from file system to html page

I'm trying do develop a very simple web app using flask, following the example from this link.
My problem is: I want to show images from my file system in that page but it seems like browsers are protected against that. I have to use something like:
<img src="http://aMessyURL.png">
Instead of being able to use something like:
<img src="images/myImageName.png">
So, I can I (dynamically) show images from my file system?
You should be able to do it when hosting a simple server:
https://docs.python.org/2/library/simplehttpserver.html
This should at least allow you to load files in the same folder as your code.
Flask interprets <img src="images/myImageName.png"> as:
app/images/myImageName.png
Normally, Flask projects have a static folder inside app (app/static) which contains your CSS, JS and images. You can either render them like above or use url_for:
<link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.png') }}">
Which renders fully as:
<link rel="shortcut icon" href="/static/img/favicon.png">
You Have to specify static root path and then use code in html below
app = Flask(__name__, static_url_path='')
In HTML
<img src="/static/images/myImageName.png">

Need basic help fixing external CSS stylesheet pathing in a Flask application

Sorry for asking such a basic question, but I'm stuck and can't figure out what I am doing wrong. I am developing a small website using Flask, teaching myself web coding along the way.
I have the following file structure:
mathsoc
mathsoc.py
mathsoc/templates
mathsoc.css
mathsoc_main.html
My mathsoc.py looks like this:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def main_page():
return render_template('mathsoc_main.html')
if __name__ == "__main__":
app.run(debug=True)
Then mathsoc_main.html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="mathsoc.css"/>
<title>Some Title</title>
</head>
<body>
<div id="content">
Hello World!
</div>
</body>
</html>
And mathsoc.css looks like this:
#content {
width:46em;
background-color: yellow;
}
But mathsoc_main.html cannot find the stylesheet, it appears: it does not apply either of the defined properties to the content. I'm guessing that I'm doing something wrong with <link rel="stylesheet" type="text/css" href="mathsoc.css"/>, but I don't know what. It seems so blindingly obvious, yet no style is loaded!
Change your folder structure to include a static folder.
mathsoc
mathsoc.py
templates
mathsoc_main.html
static
mathsoc.css
See http://flask.pocoo.org/docs/0.10/tutorial/folders/

Categories

Resources