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
Related
I am trying to run python script through html button but I am getting the following error. I don't know why. kindly help to get rid off it. The error is:
module 'sys' has no attribute 'execute'
views.py:
from subprocess import run, PIPE
from django.shortcuts import render
import requests
import sys
def external(request):
out = run([sys.execute,'/home/abc/Documents/test.py'], shell=False, stdout=PIPE)
print(out)
return render(request, 'home.html', {{'data1': out}})
home.html:
<html>
<head>
<title> RUN PYTHON SCRIPT </title>
</head>
<body>
<form action='{% url "external" %}' method="post">
{% csrf_token %}
<input type="submit" name="btn" value="start analyse" id="toggle1" onclick="location.href='{% url 'external' %}'" />
</form>
</body>
</html>
urls.py:
path('external/', views.external, name="external"),
Even the button doesn't execute the test.py python script and gives the following error:
module 'sys' has no object 'execute' in views.py
kindly help me to run script through html button
Try to use subprocess library like
import subprocess
subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
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 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");
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'}}"
Can I load template file with dynamic javascript file. For example when I render a.html, I want to load a.js
How can I do this?
If you just want to include a static javascript file, you can do it the same way that you load any other javascript file in HTML:
<script src="jquery-1.11.2.min.js"></script>
However, if what you want to do is pass in a javascript file that the template will load, depending on some backend output, something like this will work:
#views.py
from django.shortcuts import render
from django.template import RequestContext
def my_view(request):
# Logic here...
js_file = "jquery-1.11.2.min.js"
render_to_response('template.html',
context_instance=RequestContext(request,{
"js_file": js_file
}))
#template.html
<script src="{{ js_file }}"></script>