This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 1 year ago.
I have been trying for the last 45 minutes to figure out how to get my favicon on my flask page.
Here is my current code:
from flask import Flask, render_template, send_from_directory, url_for
import os
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route("/store")
def store():
return render_template("store.html")
#app.route("/games")
def games():
return render_template("games.html")
#app.route("/americanstudios")
def americanstudios():
return render_template("as.html")
#app.route("/pear")
def pear():
return render_template("pear.html")
#app.route("/favicon.ico")
def fav():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', minetype='image/vnd.microsof.icon')
if __name__ == "__main__":
app.run(debug=True)
With the base html being this:
<!DOCTYPE html>
<html>
<title>{% block title %}{% endblock %}</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font- awesome.min.css">
<head>
<link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}">
</head>
<style>
body,h1,h2,h3,h4,h5,h6 {font-family: "Raleway", Arial, Helvetica, sans-serif}
</style>
<body class="w3-light-grey">
<!-- Navigation Bar -->
<div class="w3-bar w3-white w3-large">
</i>newtech
Store
Games
American Studios
PEAR Electronics
Log In
</body>
<div class="w3-main" style="margin-left:250px">
<div class="w3-row w3-padding-64">
<div class="w3-twothird w3-container">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</html>
And this is index.html
{% extends "base.html" %}
{% block title %}newtech inc.{% endblock %}
{% block content %}
<h1 class="w3-text-teal">Home</h1>
<p>Welcome to newtech inc, where we have the coolest new items for all purposes. Whether it's a new movie to watch, or a fun game, or maybe something else, we're here for you.</p>
{% endblock %}
The only line in head in base.html should load my favicon from the static folder as the favicon for the page. But for some reason, the favicon stays as the default favicon for the index page and all other pages.
My favicon is a 64 X 64 .ico file
And it is located in my static folder
And yes the static folder is in the same directory as main.py
But even with all of this the favicon still does not show up.
And yes I am running the correct main.py
Also tried this
Yet no luck. Can anyone help me?
to look for network error, you would need to look at the network tab of the dev tools. it shows that your get for favicon.ico is failing with 404. fix? add static folder to your app (refer 1 in code), and the add get for favicon and return the file - refer 2 in code.
from flask import Flask,render_template,send_from_directory
app = Flask(__name__, static_folder='static') # 1 ( either add here or add through some os join)
import os
#app.route("/")
def home():
return render_template("index.html")
#app.route("/static/favicon.ico") # 2 add get for favicon
def fav():
print(os.path.join(app.root_path, 'static'))
return send_from_directory(app.static_folder, 'favicon.ico') # for sure return the file
if __name__=="__main__":
app.run(debug=True)
the folder structure will be like :
Did you check out the Flask documentation already? They recommend a slightly different reference than what you have there:
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/?highlight=favicon
Related
Can't seem to get my style sheet to link, can someone please tell me why?
I'm trying to set up an sample instance with a database, ran on Flask.
I thought it was my folder location, but I've double checked it is on the right place and can't figure out why, spent hours trying to fix it.
My HTML:
{% extends "layout.html" %}
{% block title %}
CS50_Web_Project1
{% endblock %}
{% block body %}
<h1>Login to CS50_Web_Project1</h1>
<form action="{{ url_for('register') }}" method="POST">
<button>Register</button>
</form>
{% endblock %}
My layout.html:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<!-- #olaf: own link to own style sheet-->
<link rel="stylesheet" href="css/style.css" type="text/css" >
<!-- #olaf: copied from https://bootsnipp.com/snippets/GaEOX-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
My CSS in css/style.css location:
/* style.css */
.note
{
text-align: center;
height: 80px;
background: -webkit-linear-gradient(left, #0072ff, #8811c5);
color: #fff;
font-weight: bold;
line-height: 80px;
}
.form-content
{
padding: 5%;
border: 1px solid #ced4da;
margin-bottom: 2%;
}
.form-control{
border-radius:1.5rem;
}
.btnSubmit
{
border:none;
border-radius:1.5rem;
padding: 1%;
width: 20%;
cursor: pointer;
background: #0062cc;
color: #fff;
}
My application.py:
import os
from flask import Flask, session, render_template, jsonify, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
#from the internet...# app.config['DATABASE_URL'] = "path_to_db"
# Check for environment variable
if not "DATABASE_URL":
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Set up database
engine = create_engine("DATABASE_URL")
db = scoped_session(sessionmaker(bind=engine))
#olaf: create a login page that has a form, containing "login" & "register" button
#app.route("/")
def index():
return render_template("index.html")
#olaf: Login button
#app.route("/register", methods=["POST"])
def register():
"""Register for the site"""
return render_template("registerSuccess.html")
To provide CSS file in your Flask template you need to use a specific method for that in your HTML template {{ url_for(STATIC_DIR_NAME, filename=PATH_TO_FILE_IN_STATIC_DIR)}}.
In your layout.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<!-- #olaf: own link to own style sheet-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" type="text/css" >
<!-- #olaf: copied from https://bootsnipp.com/snippets/GaEOX-->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
Also, if you follow the official documentation tips on the layout should do it.
But if you have a custom project setup then you might need to provide to your app where a static folder is.
For example in your application.py
import os
from flask import Flask, session, render_template, jsonify, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(THIS_DIR, 'specific_path_to_static', 'static')
app = Flask(__name__, static_url_path=STATIC_DIR)
#from the internet...# app.config['DATABASE_URL'] = "path_to_db"
# Check for environment variable
if not "DATABASE_URL":
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Set up database
engine = create_engine("DATABASE_URL")
db = scoped_session(sessionmaker(bind=engine))
#olaf: create a login page that has a form, containing "login" & "register" button
#app.route("/")
def index():
return render_template("index.html")
#olaf: Login button
#app.route("/register", methods=["POST"])
def register():
"""Register for the site"""
return render_template("registerSuccess.html")
Then the flask template should find the style.css file provided in layout.html file.
The first solution i can propose is that you download the bootstrap files and have them on your local working directory, then make a folder to contain static files and try the following code
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 6 years ago.
I reduced the code for this to, I think, minimum while trying to get it to work:
The python:
#!/usr/bin/env python
from functools import wraps
from flask import Flask, render_template, session, request, redirect, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
#app.route('/')
def index():
return render_template('index_test.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
The html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
The image is in the static folder.
And it gives this error:
"GET /bulboff.gif HTTP/1.1" 404
when the page is accessed.
I've tried several things like setting the Flask default paths, without the url_for, etc, but, still no image.
What am I missing?
According to the flask document:
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.
In your case, use <img src="{{ url_for('static', filename='bulboff.gif') }}">
If You put image in the static folder, You should use something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}static/bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
Alternatively, You could change application's code and add following:
#app.route('/bulboff.gif')
def bulboff():
return open('static/bulboff.gif').read()
<img src="{{url_for('static', filename='bulboff.gif')}}" />
Try that. Your filename could be a path from the static folder. So like if you have filename = \some\path\img.png it will look for the img in static\some\ath\img
I'm new to Flask and
I'm trying to create a Stumbleupon like website but I'm having problems while loading the content into an iFrame. I just cant figure it out how to iterate through each url and load them into the iFrame while clicking in the <a> tag.
Here is what I've done:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
return render_template('index.html', urls=urls)
if __name__ == "__main__":
app.run(debug=True)
templates/layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="/static/css/foundation.css"/>
</head>
<body>
<nav class="top-bar">
<h3 align="center">Stumble</h3>
</nav>
{% block content %}
{% endblock content %}
</body>
</html>
templates/index.html
{% extends 'layout.html' %}
{% block content %}
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="????????" frameborder="0"></iframe>
{% endblock content %}
After adding import random at the top of your app.py file you could structure your code like this:
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
iframe = random.choice(urls)
return render_template('index.html', iframe=iframe)
Then access the value in your template:
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="{{ iframe }}" frameborder="0"></iframe>
And simply set the Stumble button to refresh the page.
<h3 align="center">Stumble</h3>
This will be pretty basic, but it will have the behaviour you're describing.
An improvement will be to use the session object to make sure that two subsequent requests do not display the same page inside the iframe.
So with flask I know that I can add CSS with
<link ... href="{{ url_for('static', filename='stylesheets/style.css') }}" />
but if I am adding a google font which usually in HTML looks like
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
what do I need to edit/add for it to work with Flask?
Add the google font link to your index.html or any page that you want like this:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block styles %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename= 'mystyle.css') }}">
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
{% endblock %}
Then, add the CSS font statement to your custom CSS file (mine is static/mysyle.css) :
body {
font-family: 'Open Sans Condensed', sans-serif;`
}
You can't use static here like you would normally for a link to a resource on the webserver. Your link is still essentially static but not related to anything you are serving. So you either put the Google font link directly in the HTML template, or as a variable expanding to the full link (which would be convenient if you aren't using the same header template everywhere and may change the font later).
I currently have twitter bootstrap incorporated on my Django test site but it is not working properly.
I tested out an example of code on the bootstrap website: http://getbootstrap.com/2.3.2/components.html#labels-badges
All I had on the site is the success badge (green oval with a 2 in the middle)
<span class="badge badge-success">2</span>
However, only the oval and the "2" would be displayed but the green color round the "2" is not displayed. All I see is a grey oval with a "2" inside. Pretty much the same as the DEFAULT badge on the bootstrap website except there is a "2" instead of a "1".
I was wondering if anyone with Django and twitter bootstrap experience would help me with this issue.
Here is my views.py:
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render, render_to_response
def index(request):
return render(request,'homepage/index.html')
Here is my html file:
{% load staticfiles %}
{% load compressed %}
<!DOCTYPE html>
<head>
{% compressed_js 'bootstrap' %}
{% compressed_css 'bootstrap' %}
</head>
<html>
<body>
<span class="badge badge-success">2</span>
</body>
</html>
Thank you for all the help! much appreciated!
I think your compressed_js and compressed_css does not do the trick.
To check if everything is ok, use for exemple FireBug, then press F12 and point your mouse on the badge to see if the CSS rule is display on the left panel. Repeat this step for badge-success to try to find it.
After all of this i'll suggest a more classical way without compressed_xxx :
<link rel="stylesheet" href="{% static "bootstrap/css/bootstrap.min.css" %}" type="text/css" media="screen" />
<link rel="stylesheet" href="{% static "bootstrap/css/bootstrap-responsive.min.css" %}" type="text/css" media="screen" />
where bootstrap is the folder I put in the static one I setup in the settings.py file
Hope this will be usefull.