Accessing Django Template Variables in Javascript

How do we follow the Django DRY principle and avoid as many hard coded elements as possible in our project when we need to include Javascript? A good example of this is if we are pulling in a bookmarklet that will be offered on the site. We need to reference the domain of our project in the bookmarklet, but this then yields code buried in our project’s static files that needs to be altered by anyone that might be utilizing your open sourced code.

This example presents a little bit of a challenge. If this were HTML in our template we could simply reference a DOMAIN variable that we would feed in through a view. However, this is a static Javascript file, so how do we go about utilizing Django template variables in supposedly static Javascript?

Here is a simple method. In our HTML template, we will setup a Javascript global variable that is created to reference a template variable that we feed in from our view, here a domain, and this variable is then referenced in our static Javascript files.

<!-- Our HTML Template (templates/index.html) that is fed data from views.py -->
{% extends "base.html" %}
{% block content %}

<script type="text/javascript" src="/static/somejs.js"></script>

<script> 
var DOMAIN = "{{ site_domain }}";
</script>

<!-- rest of our template, business as usual. -->
{% endblock %}

As you can see, we would feed in a site_domain variable from views.py that might be created something like this.

from django.contrib.sites.models import Site
from django.shortcuts import render_to_response

def index(request):
    '''Our main index view.'''
    site_domain = smart_str(Site.objects.get_current().domain)
    # more of our view code...
    
    return render_to_response('templates/index.html', {
	'site_domain': site_domain,
        #...rest of our template vars
    })

Now, how do we use this in our static Javascript? We reference that global Javascript variable we declared in our template using our Django template variable site_domain.

// Our Javascript file ... /static/somejs.js 
alert("Your current domain is: "+DOMAIN);

Now our code is much more portable, even in places where things should essentially be static.

Finding Images with Python

Let’s say we wish to take a directory, the current directory in this example, and gather all the image files. This could be helpful if we were then going to use PIL or Image Magick to manipulate those files, or create a select-able list for use in a GUI, and so on…

There are countless ways we could do this, but here is one with a module that is very helpful with image details.

import os,imghdr
for f in os.listdir(os.getcwd()):
	try:
		if imghdr.what(f):
			print f
	except:
		pass

Python – Dynamically Printing to Single Line of Stdout

It’s that time again; code snippet time. This is a short and sweet bit of a code that has some really practical and powerful implications.

When handling large amounts of data processing, it’s often desirable to keep the user informed of where things are in terms of progress. However, filling up the scrollback buffer with thousands of “Completed processing [item X]” or “X % completed” is not always desirable. So, how do we handle verbosity without filling scrollback?

Here, we will print data using stdout but we will continually use the same line of the terminal. It’s extremely simple; before each data print, we will move the cursor back to the beginning of the current line, cut out the entire line of text, and then print our current bit of data.

*Note: This is using ANSI escape sequences and therefore will work on any VT100 type terminal.

 

The code:

import sys

class Printer():
	"""
	Print things to stdout on one line dynamically
	"""

	def __init__(self,data):

		sys.stdout.write("\r\x1b[K"+data.__str__())
		sys.stdout.flush()

 

To output data we might do something like:

totalFiles = len(fileList)
currentFileNum = 1.0

for f in fileList:
	ProcessFile(f)
	currentPercent = currentFileNum/totalFiles*100
	output = "%f of %d completed." % (currentPercent,totalFiles)
	Printer(output)
	currentFileNum += 1

 

And here is an example of what our output would look like in a practical scenario.

Processing some data
Progressing along with dynamic status updates

Simple. You can test it out using an ‘for x in range(1,100)’ sort of statement as well. Now we can keep a persistent display of data processing or program progress without slamming the scrollback buffer of the user’s terminal.

Working with XLS in Python

As I’m sure you are well aware, Python has modules for just about any task. That’s one of the features of the language which makes it so efficient. In science, like most technical environments, we are dealing with lots of data and often in formats or layouts which are sub-optimal.

The following example code is a quick program I wrote a while back for dealing with Excel-based data from a plate reader setup. In short, reading through the code, you can see that we merely are moving data around by iteration sets and writing this correctly ordered data to a new Excel sheet. Data was being read through and written to the original sheet sequentially by time, but we needed to have our data written out by sample set which would be offset by both the number of replicants and the number of conditions.

We use the XLRD and XLWT modules to read and write Excel files, respectively.  The iteration process for parsing the data is not exactly of great interest to you I’m sure, however, the reading and writing of the Excel files will hopefully be of some help. Also note that you can apply some styling to your newly created sheet by using the Easyxf function of XLWT.

Now, for the code.
Continue reading “Working with XLS in Python”