Displaying d3 chart in django - python

I was going through the library NVD3 and have found this as an example on the website:
d3.json('cumulativeLineData.json', function(data) {
nv.addGraph(function() {
var chart = nv.models.cumulativeLineChart()
.x(function(d) { return d[0] })
.y(function(d) { return d[1]/100 }) //adjusting, 100% is 1.00, not 100 as it is in the data
.color(d3.scale.category10().range())
.useInteractiveGuideline(true)
;
chart.xAxis
.tickValues([1078030800000,1122782400000,1167541200000,1251691200000])
.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
chart.yAxis
.tickFormat(d3.format(',.1%'));
d3.select('#chart svg')
.datum(data)
.call(chart);
//TODO: Figure out a good way to do this automatically
nv.utils.windowResize(chart.update);
return chart;
});
});
The image is something like this:
Check the live demo here: http://nvd3.org/examples/cumulativeLine.html
The json file is here: Json file for example
Now I was willing to include such charts in the django example. So I went on checking the implementation of Django-NVD3. But I could not find anything related to it and the documentation written by author is not understood by me.
Please let me know how I can include d3 chart in the django frame in real time.

Django largely is backend framework for python. That means it creates responses to html requests. These responses are rendered using templates that contain the html code which is being created on the fly.
nvd3.js or d3.js for that matter live on the frontend, i.e. the user's browser. That means all nvd3.js html and javascript code (like the one you quote) go into the Django template.
To use nvd3.js you will have to load the d3.js and nvd3.js javascript libraries and corresponding style sheets. (On how to do this, see the respective documentations.) These elements need to go to a different place in the template (html where the chart is supposed to go, css into the header and javascript at the end of the body).
django-nvd3 is a django app that is used to simplify the use of nvd3 on the front end. It is one option to work with Django and nvd3.js. It defines template tags that will include the required javascript code and style sheets in your template. The first tag include_chart_jscss will do exactly this and is supposed to be used in the <head> section of the tempalte. The second tag load_chartwill generate the javascript you quoted actually creating the chart. The third tag (include_container) will insert the required html div elements (which you did not quote in the questions). By passing the latter tags the same name the browser knows on which div tag to apply the javascript code. It does not help to distribute the code bits over the template. Also, it does not generate the code. This is left to a different package python-nvd3 which itself relies on a template engine (Jinja2) which likely is different from the one you use with Django. In a nutshell: django-nvd3 solves the problem of generating javascript code for nvd3 charts but not the problem of how to distribute that code in django templates.
I suggest Sekizai to better distribute code bits. It allows to split html, css and js bits of a page in separate blocks. Then you can use simple includes to add a chart to your web page. In the included file you may surround the required css code by {% addtoblock css %} and the required
javascript by {% addtoblock js %}. When using sekizai the base templates need to have these block ("js" and "css") defined, see the Sekizai documentation.
Of course it is a matter of opinion, but I prefer using sekizai for distributing the nvd3.js code bits in the template and making charts available as includable templates to Django (thereby refraining from the costs of a second template engine). My include templates contain the raw nvd3 code taken, e.g. from one of the examples.
I have compiled three gists which assume you have sekizai installed and included in your INSTALLED_APPS settings:
Python code for the view function. Remember to include the view function in urls.py. The code assumes that the file with the json data is in a static folder.
A template called base.html which does include the html code of the page to be rendered. It has a title and then includes the chart.
A template for the chart which is a 1:1 copy of the code in the question except that some parameters are dynamically loaded (source file, ticks).

Related

Python pisa/xhtml2pdf messy rendering

In a django project, I want to generate an html page from a view and convert the html/css generated to pdf. I am using xhtml2pdf for this (https://github.com/chrisglass/xhtml2pdf/blob/master/doc/usage.rst#using-xhtml2pdf-in-django).
Browser -> django view -> mysql DB -> django template -> html/css -> pdf
I have made sure that:
I am using a function (link_callbak) to convert all relative paths to a proper absolute ones so xhtml2pdf is able to retrieve all the images needed.
Instead of relying on a tag to include the CSS (which does not work) I have directly used #import function with an absolute path to the css file. (CSS not rendered by Pisa's pdf generation in Django)
The css file is taken into account as I find some style element in the output howver the pdf generated is very different from the html output. Images are all messed up (partly visible and partly just outside the document), forms are not respected, font size is not correct, <ul> are not properly rendered. Moreover, I had to remove a -moz-placeholder tag from the CSS as it was not properly handeled by xhtml2pdf.
Is there known issues of CSS interpretation with xhtml2pdf ? Is there restrictions ?
I already spent a lot of time customizing the CSS file to make it work on Chrome/Firefox and IE7, and I don't want to spend another round on adapting it for xhtml2pdf. Is there a reliable solution to convert an html/CSS templated through django to pdf ? Even a special type of link to call the 'print pdf' function of the browser would do...
And no, I don't want to use ReportLab and draw squares and circles, thank you !

How to make almost static site in Pyramid?

I'm switching to Pyramid from Apache/PHP/Smarty/Dreamweaver scheme.
I mean the situation of having static site in Apache with menu realized via Dreamweaver template or other static tools. And then if I wanted to put some dynamic content in html I could make the following:
Put smarty templates in html.
Create php behind html with same name. Php takes html as template.
Change links from html to php.
And that was all.
This scheme is convenient because the site is viewable in browser and editable
in Dreamweaver.
How can I reproduce this scheme in Pyramid?
There are separate dirs for templates and static content. Plus all this myapp:static modifiers in hrefs. Where to look up?
Thank you for your advices.
There is no smarty port for Python. So you would have to start using another template syntax, such as mako or chameleon
To do this, you would setup your view_config to respond to the url, end tell it to use the corresponding template.
If you want to do this, you would simple change your code. But this is not necessary, pyramid will process your requests, whether the url contains .html, .php, .python, /, or whatever.
You could still edit the templates in Dreamweaver I guess.
Only really static pages would be linked using static_url. If it is html that you mean to make into a template, it might be easiest to just start of with a template right away, without any dynamic content in it.
This is from the URL dispatch tutorial:
# in views.py
#view_config(route_name='view_page', renderer='templates/view.pt')
def view_page(request):
return {}
# in __init__.py
config.add_route('view_page', 'mypage.html')
You can build a small web application which uses traversal to serve html documents from a directory. Here's more explanations about how traversal works.
Then you can programmatically render those documents as Chameleon templates, using PageTemplateFile for example. This would allow you to include, say, common header/footer/navigation into every page.
This would mean that every page in your site will be in fact dynamic, so that would incur a small performance penalty for every page regardless of whether it has dynamic content or not, but you should not be concerned with this unless you're building the next Facebook. :) However, this approach would allow you to have a plain html document corresponding to every page in your website which you'll be able to edit using Dreamweaver or any other editor.
This is somewhat a different answer than ohters but here is a completely different flow.
Write all your pages in html. Everything!!! and then use something like angularjs or knockoutjs to add dynamic content. Pyramid will serve dynamic content requested using ajax.
You can then map everything to you html templates... edit those templates wherever you want since they are simply html files.
The downside is that making it work altogether isn't that simple at first.

Python - Want to change header logo based on url selection

I would like to change the logo of a website based on which menu is currently activated/seen by the user browsing the website.
For instance I have www.urltowebsite.com/menu1 = Header Logo 1
And then I have www.urltowebsite.com/menu2 = Header Logo 2
And on top of this I want to add an else statement stating that: If any other menu is selected, use header logo 3.
How can I make this possible with Python? I cant seem to wrap my head around what to define where and how to call up the different functions on the HTML website.
Oh and I insist doing this with Python. And preferably without any framework such as Django. But if needs be I can install web.py
EDIT:
Am I forced to go with php then? I would like to once and for all start utilizing Python on my web projects.
The website is made in simple HTML as I said first. The Javascript functions are only used to serve the HTML menu's through AJAX. Again this does not matter much for what I am trying to do, as menu's have classes and I can define those in php and thus change my logo/header.
What I want to do is to use Python in this instance. Here is a code snippet from the site:
<div id="header">
<span class="title"><img src="http://www.url.com/subfolder/images/logo.png"/>
</span>
</div>
And some more relevant to this:
<div id="menu">
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
<li>004</li>
<li>005</li>
<li>006</li>
<li>007</li>
<li>008</li>
</ul>
</div>
So can I use python here?
You're asking to do the wrong thing the wrong way.
In order to change the logo based on the URL in Python , you need Python to generate the page and know what that url is.
There are two ways to do that in Python:
Use an existing Web Framework
Write your own Web Framework
"Python" doesn't know or care what your URL is - the frameworks and support libraries ( Django, Pyramid, Bottle, Flash, Tornado, Twisted, etc) figure out what the URL is by an integration with an underlying web server ( though some have their own webserver coupled in ). Similarly, PHP doesn't really know or care what the URL is - that information comes from an integration with Apache or FCGI/Nginx/etc. PHP tends to ship with most/all of that integration done. It's also worth noting that PHP is not just a language, but a web framework. Python is just a language.
Most Python frameworks will be written to the WSGI spec and have a "request" object that has all the data you want ( and many use the WebOb librbary for that ).
If you plan on doing everything with static HTML files, then you have a few options:
have a single static directory. use javascript to figure out the addressbar location, and render the corresponding logo / write the headers & footers.
have a "template" directory of all your HTML. use a Python script build a static version of each website with the custom headers/footers and configure your webserver to serve a different one for each domain.
No, Python cannot run inside the HTML web page. If you're really serving plain HTML pages then you must use javascript to execute code in the browser once the page is loaded. However, since you mention using AJAX, it sounds like it's not really true that you're serving plain HTML but rather have some server side code. If so, that server side code is the place to put your HTML-construction logic. To know the best way to do that, you would have to describe what's happening on the server.
Although I haven't used it, I have heard that the pyhp project more or less provides php-like embedded functionality for python.

Embed Flask page in another without code duplication?

I have a page (located at /games/compare/) and it's a mini image comparison game. Users are shown two images and asked to pick between them in response to a question. This page can get images from the database, render a template with javascript and css inside and communicate back to the database using AJAX.
Now what if I wanted to embed this voting game onto the main page without duplicating any code? Ideally, I'd update the game and all the pages that "feature" the game will also reflect the changes.
I'm getting hung up on how to manage the assets for the entire site in a coherent and organized way. Some pages have css, javascript and I'm also using frameworks like bootstrap and a GIS framework.
Would I set the game up as a blueprint? How would I organize the assets (Javascript and CSS) so that there is no duplication?
Currently, I have a page rendering a template (main.html) which extends another (base.html). Base.html includes header.html, nav.html and footer.html with blocks set up for body and others.
My current approach is to strip everything out at the lowest level and reassemble it at a highest common level, which makes coding really slow. For instance, I have that voting game and right now it's located in a page called voting_game.html and has everything in it needed to play the game (full page html, styles and javascript included). Now if I want to include that game on another page, like the root index, the only solution I know of is to strip out the style, js and full page html from voting_game.html, leaving only the html necessary for the game to run. When I'm creating the index now, I'll import the html from voting_game.html but I'll separately have to import the style and javascript. This means I have to build every page twice, which is twice the work I need to be doing. This process also leaves little files all over the place, as I'm constantly refactoring and it makes development just a bookkeeping nightmare.
There has to be a way to do this and stay organized but I need your help understanding the best way to do this.
Thanks,
Phil
Edit: The embedded page should also be able to communicate with its parent page (the one it is being embedded into), or with other embedded pages within the same parent (children of a parent should be able to talk. So when someone plays the embedded game, they earn points, which should show up on another part other page, which would update reflecting the users current points.
This "Score board" would also be a separate widget/page/blueprint that can be embedded and will look for certain pieces of data in order to function.
To re-use a chunk of HTML, you can use Jinja's {% include %} tag. If that's too limiting, Jinja macros are also well suited. You can define your macros in a separate file and import them with {% import "path/to/macros.html" as my_macros %}.
Flask-Assets can help with the organisation of your assets.
As for using Blueprints, yes you should use them. But they mostly apply to Python code and HTML templates are organised in a different realm, so maybe their use is unrelated here.
You can't always remove all duplication though. If your game needs to affect three distant locations of the server-generated HTML, that's bits of template code to copy in every template that includes your game.

Python Templating and Ajax

I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
#app.route('/home')
def userhome():
data=go get user details from the database
return render_template("home.html",userdata=data)
Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template.
However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript).
The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks.
I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here.
Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.
You have two options: template on the server, or template in the browser.
To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.
To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are lots of jQuery templating solutions, for example.
I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.
In the home.html template, I'd do something like
<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>
And keep the actual markup in _user_details.html. This way, for an AJAX request you just render the _user_details.html partial only.

Categories