I'm having an issue when using Flask and it's templates when importing Scripts and Stylesheets. I searched everywhere how to do it, and none of them solved my problem.
This is my project's structure:
https://i.gyazo.com/f746c58499cbbafa11b023eecb316b15.png
This is how I defined Flask's configuration:
app = Flask(__name__,
template_folder="../web/templates",
static_folder="../web/static",
static_url_path=''
)
And this is how i'm importing the scripts :
<script src={{ url_for('static', filename='/js/home.js') }}></script>
And this is the msg I get :
Falló la carga de con fuente “http://localhost:5000/js/home.js”.
(Basically says that it failed loading that script)
I already read the Quickstart guide from Flask.
I tried creating a "static" folder in the project's root and not setting anything on the config. Tried to change the static folder everywhere on my project.
Can anyone help me solve this? I'm new to Flask and Jinja, but have been searching the whole day and can't make it work.
NOTE : The path for the templates work, my templates work fine, except for .js and .css imports.
you need to remove starting '/' from <script src={{ url_for('static',filename='/js/home.js') }}.
so change it to <script src={{ url_for('static',filename='js/home.js') }}.
your project structure should look like this:
MyFlaskApp/templates/home.html
MyFlaskApp/static/js/home.js
MyFlaskApp/app.py
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def home():
return render_template("home.html")
if __name__ == "__main__":
app.run()
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src={{ url_for('static',filename='js/home.js') }}> </script>
</body>
</html>
home.js
alert("hello");
Related
I am attempting to use flask to access a csv file and two json files which are being held in a folder named static. Even though i have mentioned the static folder in my code i am still having the following 404 issues with my map.js file running.
"GET / HTTP/1.1" 200
"GET /%7B%7B%20url_for('static',%20filename%20=%20'topo_E08000025.json')%20%7D%7D HTTP/1.1" 404
"GET /%7B%7B%20url_for('static',%20filename%20=%20'/static/sampleproperty3.csv')%20%7D%7D HTTP/1.1" 404
"GET /%7B%7B%20url_for('static',%20filename%20=%20'/static/sampleproperty3.csv')%20%7D%7D HTTP/1.1" 404
I have looked everywhere but can't seem to figure out what is going wrong.
I would like the code to pick up on the data in my static folder rather than returning a 404 error.
python code:
from flask import Flask,render_template, url_for
app = Flask(__name__)
#app.route('/')
def index():
return render_template('map.html')
if __name__== '__main__':
app.run(debug=True)
map html code:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://rawgit.com/nstrayer/slid3r/master/dist/slid3r.js"></script>
<script src = "https://unpkg.com/topojson#3.0.2/dist/topojson.js"></script>
<script src = "https://d3js.org/colorbrewer.v1.min.js"></script>
<script src = "{{ url_for('static', filename = 'mapFunctions.js') }}"></script>
<link rel="stylesheet" href= "{{ url_for('static', filename = 'map.css') }}">
</head>
<body style = "background-color:gray">
<script src = 'static/map.js' ></script>
</body>
map javascript code:
const svgHeight = 550;
const svgWidth = $(window).width(); // Uses Jquery to find the width of the window and set the svg width to that so it fills up the entire window
const svgPadding = 500;
let active = d3.select(null);
let filteredData ;
let radicusScale ;
let selected;
let originalTranslation ;
let locationLsoas = d3.json("topo_E08000025.json");
let locationWards = d3.json("topo_ward.json");
let properties = d3.csv("sampleproperty3.csv");
HTML files rendered using render_template shall be under templates folder and not static.
The files (CSS/JS) used by these HTML files, shall be under static folder.
I strongly recommend using an IDE like PyCharm and start with a blank flask project. That will give you a template to begin with.
For your reference, a sample hierarchy should be like this:
|static/
|---css/
|------style.css
|templates/
|---index.html
|app.py
My code for app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template("index.html")
if __name__ == '__main__':
app.run()
My code for index.html (notice the way I access the css files):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}" type="text/css">
</head>
<body>
<h1>Header</h1>
</body>
</html>
Hope this helps. Good luck.
I would like to make use of a javascript library (specifically this one) in my Bokeh javascript callback. How can I specify importing of this javascript library such that the library is accessible from Bokeh's js callback functions?
The examples at:
https://docs.bokeh.org/en/latest/docs/user_guide/extensions.html
mainly talk about creating a custom Bokeh Model. I am not particularly interested in creating a new Model, just want to use the library functions in a callback to modify the data that is plotted.
There are two ways:
Server app
Standalone HTML app
Here is how:
Server app:
You can create a Bokeh server directory structure.
create a directory called myapp
name your Python script main.py and put it there
create a subdirectory there called templates
create index.html, main.js and optional styles.css files and put them in templates subdirectory
open terminal, navigate to directory one level higher than myapp directory and start your app with this command: bokeh serve --show myapp
The following example works for Bokeh v1.0.4.
Directory structure:
myapp
|
+---main.py
+---templates
+---index.html
+---main.js
+---styles.css
main.py
from bokeh.plotting import curdoc
from bokeh.models import Button, CustomJS
button = Button(label = 'Click Me')
button.callback = CustomJS(code = """ alert($) """)
curdoc().add_root(button)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta charset="utf-8">
{{ bokeh_css }}
{{ bokeh_js }}
<style>
{% include 'styles.css' %}
</style>
</head>
<body>
<script>
{% include 'main.js' %}
</script>
{{ plot_div|indent(8) }}
{{ plot_script|indent(8) }}
</body>
</html>
Please note that this way you can include local, but also remote JS libraries or style sheets.
main.js
$(document).ready(function() {
alert('jQuery succesfully loaded !')
});
styles.css
body { background: #111122; }
> Standalone HTML app:
import os
from bokeh.io import save
from bokeh.models import Slider
from bokeh.util.browser import view
template = """
{% block postamble %}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function() {
var slider = Bokeh.documents[0].get_model_by_name('my_slider')
alert('slider value: ' + slider.value)
});
</script>
{% endblock %} """
slider = Slider(start=0, end=10, value=5, name='my_slider')
save(slider, template=template)
view(os.path.join(os.path.dirname(__file__), os.path.basename(__file__)).replace('.py', ".html")
I'm using the built-in flask server and I want to show an animated pie chart, like here:
http://codepen.io/tpalmer/pen/jqlFG
or
http://jsfiddle.net/thmain/xL48ru9k/1/
For simplicity, I use the latter one.
The python flask server code is:
from flask import Flask, render_template, request, flash
from forms import ContactForm
app = Flask(__name__)
app.secret_key = 'blah'
#app.route('/', methods = ['GET', 'POST'])
def test():
return render_template('test.html')
if __name__ == '__main__':
app.run(debug = True)
I did copy the javascript code provided on the webpage to the file static/script2.js
and the css code to static/css/style_d3.css
My HTML code is
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="//style_d3.css" type="text/css">
</head>
<body>
<p>test</p>
<div class="animated-ring">
<svg></svg>
</div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//script2.js"></script>
</body>
</html>
I run the webpage through the flask server. But I get a webpage that just says "test", there's no chart.
What do I do wrong?
I'd really appreciate if someone could help me.
You only render the test.html at "/" path, the script2.js needs to be rendered too at "/script2.js".
Try this one liner at your project's root directory to host all files:
python -m SimpleHTTPServer
I think you need to set to a path your js file. In your app dir create a static folder then put your script2.js file and when you call this file at html use flask url_for() function
src="{{url_for('static', filename='script2.js'}}"
When the gray div is clicked I want the website to be opened in a new tab, but here this javascript code isn't working. Why? How I can edit it?
views.py:
from django.shortcuts import render
from django.http import HttpResponse
def test(request):
return render(request, 'test.html')
test.html:
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#gray").click(function(){
window.open("http://www.w3schools.com");
});
});
</script>
</head>
<body>
<div id='gray' style="width:100px;height:100px;background:gray;"></div>
</body>
urls.py:
from django.conf.urls import include, url
from secondv.views import test
urlpatterns = [
url(r'^test', test),
]
The jquery.min.js file is in the template directory, the same directory as test.html file.
Template directory is only for templates. All static content such as js, images should be placed to static directory. It's well described in docs
https://docs.djangoproject.com/en/1.9/intro/tutorial06/
https://docs.djangoproject.com/en/1.9/howto/static-files/deployment/ - for production
This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 6 years ago.
Hey I've got the following problem:
I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:
Assume I have a simple flask web app called app.py located in my_app/ which looks like this
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
and the corresponding index.html, which is located in my_app/templates, is simply
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
then I see the expected result, that is, i can click on the paragraph to make it disappear.
BUT: I would like to put the javascript part into a main.js file under static/js/. like so:
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
and the index.html becomes:
<!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!
Simply invoke the url_for function within the template, referencing the special static endpoint so that the correct url to the desired target resource be created. As the desired target is the main.js file inside static/js, this would lead to the following:
<script type=text/javascript src="{{
url_for('static', filename='js/main.js')
}}"></script>
The rest of the quickstart guide contains additional useful information.