I'm new to django and bokeh.
I was trying to render a simple bokeh plot supported by a few select options that essentially allow me to tweak my plot's content in a django web application.
The plots are rendered when the script and div elements obtained from the bokeh.embed.components() are passed to the template as context variables.
The same didn't work when i had a widget and a plot held in a bokeh.io.vform object.
I get the output right when i perform a bokeh.io.show(), by specifying the bokeh.plotting.output_file(), but I'm trying to get this running in my web application.
Am I missing anything? Or is there any other approach that serves my intent?
my code to just render a bokeh widget is as follows:
views.py
#django imports
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.io import vform
from bokeh.models.widgets import Select
def test(request):
s = Select(title="test", value="a", options=['a','b','c'])
script,div = components(s)
return render(request,'test.html',RequestContext(request,{'script':script,'div':div}))
test.html
<html>
<head>
<link href="http://cdn.bokeh.org/bokeh/release/bokeh-0.11.1.min.css" rel="stylesheet" type="text/css">
<script src="http://cdn.bokeh.org/bokeh/release/bokeh-0.11.1.min.js"></script>
</head>
{% load staticfiles %}
<body>
{{ div | safe }}
{{ script | safe }}
</body>
</html>
I would expect a select form element to be rendered when test.html is launched from test() in django. but doesn't happen.
BokehJS was recently split up into separate pieces to provide more flexible options for usage depending on what parts of the library are actually being used. Because loading resources is normally automatically handled in many cases, it was unintentioinally neglected to mention this split prominently in the docs. However, it is important to know about for embedding. There is an issue to update the docs, but what you need to know is that if you are using widgets, you now also need to load additional scripts from CDN:
http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.11.1.min.js
http://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.11.1.min.css
Related
I have a script which takes uploaded data, munges it together, turns it into a plot (using Bokeh) and then exports it to a directory as JSON.
At some point in the future, a user can hit the right URL and the appropriate plot should be displayed to the user as part of the HTML template.
I can generate the plot. I can save it as JSON. I can get the URL to retrieve it as JSON, but I cannot get the JSON plot to render within the template.
I've had a dig around the Bokeh documentation and examples, but they all seem to use a flask app to serve the pages.
I think I'm on the right track, using views.py to find and return JSON as part of a render() response, and then have Bokeh.embed.embed_items() do the work in the template to make it look right, but it's not working out - everything but the plot is displayed.
1) Create the plot and puts it in the directory for later use (app/results/1)
create plot.py
import os
import json
from django.conf import settings
from bokeh.embed import json_item
from bokeh.plotting import figure
x=[1,2,3,4,5]
y=[0,-1,-2,3,4]
p=figure(title="test_example")
p.line(x, y)
#json_export = json_item(p, "result")
json_export = json_item(p)
with open(os.path.join(settings.RESULTS_DIR,"1", "test.json"), 'w') as fp:
fp.write(json.dumps(json_export))
2) Set up the url
urls.py
urlpatterns=[
path('result/<int:pk>', views.resultdetailview, name='result-detail'),
]
3) Take the request, use the pk to find the plot json and render it all in the appropriate template.
views.py
def resultdetailview(request, pk):
results=str(pk)
with open(os.path.join(settings.RESULTS_DIR, results, "test.json"), 'r') as fp:
#data=json.load(fp)
data=json.loads(fp.read())
#context={'result':data}
#return render(request, 'app/sandbox_detail.html', context)
return render(request=request,
context={'json_object':data, 'resources':CDN.render()})
NB: If I instead use return JsonResponse(data, safe=False) then the url returns the json successfully ...
I think therefore that the issue is in the template.
4) Show the wonderous plot to the user
sandbox_detail.html
<header>
<link rel="stylesheet" href="http://cdn.bokeh.org./bokeh/release/bokeh-0.11.1.min.css" type="text/css" >
<script type="text/javascript" src="http://cdn.bokeh.org./bokeh/release/bokeh-0.11.1.min.js"> </script>
</header>
<h1> Title: Test </h1>
<div>Test</div>
<body>
<div id="result"></div>
<script>
Bokeh.embed.embed_item({{json_object}}, "result");
</script>
</body>
This template renders everything but the 'result' div.
What have I missed?
This is what I see so far:
FIRST: You are mixing 2 methods for injecting plot json data into the page.
According to documentation you can do it using either of these two methods:
1) specify the div directly:
Python: json_data = json.dumps(json_item(p, "myplot"))
JavaScript: Bokeh.embed.embed_item(item);
2) specify the div in embed_item function:
Python: json_data = json.dumps(json_item(p))
JavaScript: Bokeh.embed.embed_item(item, "myplot");
But not both of them at the same time. Could this be the problem?
SECOND: Preferably don't insert Bokeh resources by hand: rather use CDN.render() or INLINE.render() to automatically include all that your script needs:
import json
from bokeh.resources import CDN
return render(request = request,
template_name = 'app/sandbox_detail.html',
context = { json_object = json.loads(json_string),
resources = CDN.render() } )
sandbox_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{{ resources }}
</head>
<body>
<div id="result"></div>
<script>
Bokeh.embed.embed_item({{ json_object }}, "result");
</script>
</body>
</html>
THIRD: Make sure what you embed in the page is json object not a string (see variable naming above)
It helps when you debug your rendered template in your browser's debug tool.
I tried a very similar approach and found one large flaw: My browser noted that it could not find the None object. The reason here is that python stores the empty value as None, while JavaScript expects a null object.
The solution? Python already translates None to null, when you run json.dumps. To keep it that way, read the json string as a string. So instead of your data=json.loads(fp.read()) use data=fp.read().
The idea is that user push the button and Flask should add some content on the page.
In my case python and Flask is not an aleatory choice, because Python make a lot of backdoor work (that for example js can't).
And perfectly it should be just one page without redirection on another page.
So my question is:
How to get the moment when user push the button and run the function I want
How to make this function add some generated content on the page without reloading.
As one of the commenters said, you are missing some key concepts in the web development stack you are working with. Lemme try to explain.
Flask is a backend framework/server. It receives requests from your browser and generates and sends a response. Your browser can make a request and load the response as a new page.
JavaScript runs in the browser (or to use a more generic term frontend). It can make changes to the way the current page looks and behaves without reloading. It can make requests to the backend, process the results it receives and act on them.
There are two basic ways browser makes a request to the backend. When you load a page. And when your Javascript code makes an XHR request.
There are three basic ways your frontend does things in response to user actions.
Run some javascript and do something without making any requests. For example, highlight a button user is hovering his mouse over, autocomplete what user is typing from some pre-defined list, switch UI tabs, hide/show elements etc.
Make a request to the backend and load the results as a new page. For example, follow a link to a new page on the site, submit a form, reload the page etc. This is how most web applications used to work 10-15 years ago.
Run some javascript and use it to make a request to the backend in the background. Use javascript to process the results and update the page dynamically without reloading. This is how most web applications work now.
Basically, there are two ways to do what you want, the old way, where you have your Flask app generate the whole page with your new content and send it to the browser. This will make the browser reload the page. And the new way, where your Flask app just provides the data you want to change and the javascript in teh browser makes an XHR request in the background and uses the data to update the page. This can happen without a reload and this is the way most modern web apps work.
I hope this clears things up for you a bit.
app.py
from flask import Flask,render_template,request
app = Flask(__name__)
#app.route("/add_item")
def add_item():
#in reality you are doing something else i imagine
return "<li>%s</li>"%(request.args.get('name'))
#app.route('/')
def hello_world():
return render_template('index.html',items=["Item 1","Item 2","Item 3"])
if __name__ == '__main__':
app.run()
templates/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
<ul id="items_holder">
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<button id="do_something">Do Something</button>
</body>
<script src="/static/app.js"></script>
</html>
static/app.js
$(function(){
$("#do_something").click(function(){
var item_name = prompt("enter item name")
$.get("/add_item?name="+item_name,function(result_data){
$('#items_holder').append(result_data)
})
})
})
I'm trying NOT to write same code twice on different templates. Real hassle when changing something.
So when I go to a section of the webpage, I want to display a side menu. This side-menu is suppose to be on several templates. Like index.html, detail.html, manage.html and so on.
But the section is only a part of the webpage, so I can't have it in base.html.
I was thinking about using include. But since the side menu is dependent of DB queries to be generated, I then have to do queries for each view. Which also makes redundant code.
What is best practice for this feature?
Cheers!
You could write custom inclusion_tag, that's more feasible for the scenario:
my_app/templatetags/my_app_tags.py
from django import template
register = template.Library()
#register.inclusion_tag('side_menu.html')
def side_menu(*args, **kwargs):
# prepare context here for `side_menu.html`
ctx = {}
return ctx
Then in any template you want to include side menu do this:
{% load side_menu from my_app_tags %}
{% side_menu %}
For example, when I add custom ModelView:
class TaskModelView(ModelView):
pass
flaskadmin = Admin(name='Flasky', template_mode='bootstrap3', index_view=MyAdminIndexView(),
base_template='admin/mymaster.html')
flaskadmin.add_views(TaskModelView(models.Task, db.session))
I also get useful datepicker widget on appropriate DateTime fields:
But what about custom views and forms? I tried to add view same way, but inherited it from BaseView, then I created new form with DateTimeField from flask-admin and tried to render it:
from flask.ext.admin.form import DateTimeField, DatePickerWidget, DateTimePickerWidget
class AssebledChartForm(Form):
date_from = DateTimeField('From', format='%d.%m.%Y', widget=DateTimePickerWidget())
date_to = DateTimeField('To')
class AnalyticsView(BaseView):
<...>
return self.render('admin/analytic.html', form=form)
flaskadmin.add_view(AnalyticsView(name='Analytics', endpoint='analytics'))
but widget did not appear both on from and to fields:
How do I use flask-admin datepicker on my own forms?
You have to import DateTimePickerWidget like this:
from flask_admin.form import DateTimePickerWidget
and use it, for example, like this:
start = DateTimeField('Start', widget=DateTimePickerWidget())
As far as I remember, you can use either jQuery datepicker for this, or WTForms one, and not a flask.ext.admin.form.
Admin form is intended to be hidden from the end user, and exposing its API to the public user is strongly prohibited.
There was a similar question here
And you can see a good example on how to use WTForms DatePicker.
Your admin/analytic.html is not loading the javascript that handles the client side selection of dates. add the following to your template;
{% block tail_js %}
<script src="/static/vendor/jquery.min.js" type="text/javascript">/script>
{# use /static/bootstrap2/js/bootstrap.min.js if you are using bootstrap2 #}
<script src="/static/bootstrap3/js/bootstrap.min.js" type="text/javascript"></script>
<script src="/static/vendor/moment.min.js" type="text/javascript"></script>
<script src="/static/vendor/select2/select2.min.js" type="text/javascript"></script>
{% endblock %}
This should give you everything you need to make all the widgets work (Select2, DatePicker, etc).
I am using django-summernote editor for creating posts with text and images which are saved in a character field as HTML tags.
I want to add a read-more functionality where a limited sized preview is shown for all the posts. An idea could be to truncate the character field, but it may lead to truncation of HTML image tags if they happen to be positioned between the boundary.
How to get around this?
Django has two template filters you can use to make sure your HTML doesn't get malformed: truncatechars_html and truncatewords_html
Template filters are just functions, so you can import them anywhere you need in your Python code and assign the result to a variable you can use elsewhere, etc.
Example:
from django.template.defaultfilters import truncatechars_html
html = """<p>Look, I’m some HTML. You can truncate me
with Django template filters</p>"""
truncated_value = truncatechars_html(html, 30)
I'm late to this party but this post came up in search results. I just got a working solution to this myself with a custom template filter. This allows you to drop in the break on a case by case basis like WordPress. Here is what I did (with help from this post and the Django docs):
Sample post submitted in a textfield:
<p>Here is some sample text</p>
<!--more-->
<img src="cool_photo.jpg" />
in templatetags/read_more.py
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
#register.filter(name='read_more')
#stringfilter
def read_more(value):
pattern = "<!--more-->"
return value.split(pattern, 1)[0]
in the template that's rendering the truncated version:
{% load read_more %}
{{ object.body|read_more|safe }}
Since the split pattern is an html comment there's no need to cut it from the main post body template:
{{ object.body|safe }}