I'm trying to show a background image using python flask and html. But I get the error "Failed to load resource: the server responded with a status of 404 (NOT FOUND)" My structre I think is good but heres the code.
home.py file
from flask import render_template, Blueprint, request, send_file
home_page = Blueprint('home', __name__)
#home_page.route('/', methods=['POST', 'GET'])
def home():
return render_template('index.html')
return send_file ("home_bg.jpg")
index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>poo</title>
<style>
</style>
</head>
<body style="background-image: url(/static/home_bg.jpg);">
<script>
</script>
</body>
</html>
I think it has something to do with returning the picture to the client in the home.py file.
Change the URL to this style
background-image: url({{ url_for('static',filename='img/home.jpg') }})
To learn more about this here is the documentation:
http://flask.pocoo.org/docs/1.0/tutorial/static/
You must change the home view function and remove the last line, because firstly this line will NEVER be executed, and secondly it is simply not necessary, the flask distributes static files itself, you should not do it manually
The line from the template where you upload the image should be changed to the following:
background-image: url( {{ url_for('static', filename='home_bg.jpg') }} )
Also see:
About Static Files
About url_for function
And about url building in flask using url_for
Related
How can i repair errors with my path? I would like my html in a flask to load my stylesheet into the project, but it throws a lot of jinja2 errors. I'm starting with flask framework.
from flask import Flask, redirect, url_for, render_template
import os.path
TEMPLATE_DIR = os.path.abspath('PROJECTS DEV\Extractor_APP\templates')
STATIC_DIR = os.path.abspath('PROJECTS DEV\Extractor_APP\static\styles')
app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)
#app.route("/")
def home():
return render_template("homepage.html")
#app.route("/<name>")
def name(name):
return render_template("namepage.html")
if __name__ == '__main__':
app.run(debug=True)
<html>
<head>
<title>Flask learning</title>
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/homepage.css') }}">
<title>Home page</title>
</head>
<body>
<h1>Home page!</h1>
{% for text in content%}
<p>{{text}}</p>
{% endfor %}
</body>
</html>```
In the root folder of your project, create a static folder for static files like css and js files. See example below:
To generate URLs for static files, use the special 'static' endpoint
name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
https://flask.palletsprojects.com/en/2.1.x/quickstart/#static-files
There is also no need to specify static and template folders. Just use: app = Flask(__name__)
I have a form on one page that I want to submit to another page. I can't figure out how to create the link to that second page.
Project layout:
Fileserver/
config.py
requirements.txt
run.py
setup.py
app/
__init__.py
static/
css/
img/
js/
templates/
formAction.html
formSubmit.html
index.html
__init__.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
ip = request.remote_addr
return render_template('index.html', user_ip=ip)
index.html:
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li>Check Out This Form!
</ul>
</body>
</html>
I can see the page at localhost:5000/ without issue.
I have also tried:
as well as:
What am I missing?
url_for generates urls to routes defined in your application. There are no (or should probably not be any) raw html files being served, especially out of the templates folder. Each template should be something rendered by Jinja. Each location you want to display or post a form to should be handled and generated by a route on your application.
In this case, you probably want to have one route to both render the form on GET and handle the form submit on POST.
__init__.py:
from flask import Flask, request, url_for, redirect, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
if request.method == 'POST':
# do stuff when the form is submitted
# redirect to end the POST handling
# the redirect can be to the same route or somewhere else
return redirect(url_for('index'))
# show the form, it wasn't submitted
return render_template('cool_form.html')
templates/index.html:
<!doctype html>
<html>
<body>
<p>Check out this cool form!</p>
</body>
</html>
templates/cool_form.html:
<!doctype html>
<html>
<body>
<form method="post">
<button type="submit">Do it!</button>
</form>
</html>
I don't know what your forms and routes actually do, so this is just an example.
If you need to link static files, put them in the static folder, then use:
url_for('static', filename='a_picture.png')
So what I just found was that if I don't wrap the href in parenthesis it works and I also created a link to return back a page
#app.route('/blog')
def blog():
return '<h1>These are my thoughts on <a href=blog/2020/dogs>dogs</a></h1>'
#app.route('/blog/2020/dogs')
def blog2():
return '<h3>these are my dogs <a href=../../blog>home</a></h3>'
The following code works perfectly from the .py file but I want to separate the HTML and put it in templates/index.html.
I suppose I have to use the render_template function in Flask to be able to return the same results.
# File dynamic_website.py
from owlready2 import *
onto = get_ontology("bacteria.owl").load()
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def ontology_page():
html = """<html><body>"""
html += """<h2>'%s' ontology</h2>""" % onto.base_iri
html += """<h3>Root classes</h3>"""
for Class in Thing.subclasses():
html += """<p>%s</p>""" % (url_for("class_page", iri = Class.iri), Class.name)
html += """</body></html>"""
return html
I created a folder template and a file index.html. I used return render_template('index.html') but it doesn't work. What arguments do I have to add to the return_template function? "for Class in Thing.subclasses():" have to be in the .html file or .py file? What about the url_for function?
If you could edit the .py code and let me know what should I write exactly in the index.html file to have the same results it would be great.
UPDATE:
What I have done:
Python code
from flask import Flask, render_template
from owlready2 import *
from flask import Flask, url_for
onto = get_ontology("bacteria.owl").load()
app = Flask(__name__)
#app.route("/")
def ontology_page():
for Class in Thing.subclasses():
return render_template('index.html')
Html code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>{{ Class.name }}</h1>
</body>
</html>
You can't return a function multiple times. Whatever is returned, is the value of the function. This tutorial is in JS, but it implies the same concept as python does.
If you want the user to see a list of things on the html, do this. render_template('index.html', things=Thing.Subclasses()) This will give Jinja a list, where it can then for loop.
For html you can do this
{% for s in things %} {{ s }} is something {% endfor %}. Do anything you want with the s though, s is one subclass from the list.
I am unable to find exact path of .css file in my flask app. Following is relevant code
layout.html
<!DOCTYPE html>
<html>
<head>
<title>An App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div id="container">
<div id="heading"><h3>App</h3></div>
{% block content %}{% endblock %}
</div>
</body>
</html>
+app
+static
style.css
+templates
__init__.py
forms.py
models.py
views.py
db_repository
.gitignore
app.db
config.py
db_create.py
The one with + sign are folders
Update:
I tried this in __init__.py, same result
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
app.config.from_object('config')
app._static_folder = os.path.abspath("static/style.css")
print os.path.abspath(app._static_folder)
db = SQLAlchemy(app)
from app import views, models
The link http://127.0.0.1:5000/static/style.css gives 404 error
Static should be on the same level as templates, not under app. Have you tried that?
I you want to change the route to the static asset's folder you could do:
app = Flask(__name__, static_folder='app/static')
check this here
I have following structure of my project:
templates
index.html
static
style.css
testFlask.py
I try to add style.css (with url_for, or manually), but url localhost:5000/static/style.css says Page not found
Here code from testFlask.py:
from flask import Flask, render_template, request, session, g, redirect, url_for,flash
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
Code from index.html:
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
Finally, I recreated my style.css and now everythings is fine.
Thanks for attention!
i tested your code/template snippets here with flask 0.8 (the version from the Debian package) and i cannot reproduce the problem -> the style.css is found.
Maybe permissions on static directory are to restrictiv? If i remove read access to the static directory for the user that runs testFlask.py the 404 appears.
best wishes,
Matthias