Switching stylesheets with Django
So I wrote some software that outputs test results in a simple xml format, which can be converted to preferred formats (csv, brief and verbose html) with xslt. These results are calculated with every commit, and archived along with lots of other data from the build.
I set up a Django-based site to provide a view over this archived data, and I wanted a simple way to choose the stylesheet used when displaying any test results. The following gives a dropbox which selects the stylesheet - there’s no AJAX here, so the whole page is served up again when you change the stylesheet, but that’s fine for my purposes.
The template html code (referred to as form.html in view code):
{% extends "template.html" %}
{% block content %}
{{ form }}
{{ data|safe }}
{% endblock %}
and the corresponding view code:
from django import forms
import libxml2
import libxslt
#'stylesheet', 'name as displayed in dropbox'
VIEW_CHOICES = (
('to_html_table.xslt', 'Table'),
('to_html.xslt', 'Detailed'),
('to_csv.xslt', 'CSV'),
)
def apply_xslt(xml_filename, xslt_filename):
styledoc = libxml2.parseFile(xslt_filename)
style = libxslt.parseStylesheetDoc(styledoc)
try:
doc = libxml2.parseFile(xml_filename)
except:
# You'll probably want to do some custom handling here
return ""
result = style.applyStylesheet(doc, None)
return str(result)
def display_results(request, build_id):
#build_id is taken from the URL only for finding the correct xml file
#if you're adapting this, you might like to omit it during testing
#and hard code the file names
if request.method == 'POST':
f = ContactForm(request.POST)
if f.is_valid():
xsltfile = f.cleaned_data['view_type']
else:
raise forms.ValidationError('Problem with requested view')
else:
xsltfile = VIEW_CHOICES[0][0]
f = ContactForm() #could set initial here if you like
(xmlfilename, xsltfilename) = get_filenames(build_id) #provide your own files!
transformed = apply_xslt(xmlfilename, xsltfilename)
return render_to_response('builds/form.html', {'form': f, 'data': transformed})
Point something in urls.py to display_results, and you’re finished.