20seven

Devigner blog about development and design

PDF Generation With PISA in Django

Today I had to come up with pdf generation for a project and was happy to find Pisa makes this cake-work. Pisa depends on Reportlab but you don’t have to dig into Reportlab to get your pdf generated.
h3. Setup

Go grab a copy of Pisa and if you don’t have Reportlab, grab that too while you’re at it. Install both then we’ll move on.

Nuts and Bolts

Create a standard html template for your view. Below is a sample of my template.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
	@page {
		size: ;
		margin: 1cm;
		@frame footer {
    		    -pdf-frame-content: footerblock;
    		    bottom: 1cm;
    		    margin-left: 1cm;
    		    margin-right: 1cm;
             margin-top: 1cm;
    		    height: 1cm;
		}
	}
</style>
</head>
<body>
<div>
    <h2></h2>
    <div></div>
</div>
<div id="footerblock">
    <pdf:pagenumber>
</div>
</body>
</html>

The template is pretty self-explanatory but the pager block will paginate your pdf.

For your view, do something like the following to create the pdf. The article function gets the article from the database and passes it on to write_pdf to generate the pdf from the html template we created earlier.


from django import http
from django.template.loader import get_template
from django.template import Context
import ho.pisa as pisa
import cStringIO as StringIO
import cgi

def write_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(
        html.encode("UTF-8")), result)
    if not pdf.err:
        return http.HttpResponse(result.getvalue(), \
             mimetype='application/pdf')
    return http.HttpResponse('Gremlin's ate your pdf! %s' % cgi.escape(html))

def article(request, id):
    article = get_object_or_404(Article, pk=id)

    return write_pdf('dtd/pdf/template.html',{
        'pagesize' : 'A4',
        'article' : article})

[NOTE: I ran into issues with the prior encoding ISO-8859-1 where it blew up on quotations. UTF-8 is working better for me.]

A couple of things to point out here. Pagesize defaults to A4. From what i can tell this seems to be set in Reportlab not Pisa. write_pdf will get your template passing your context, encode it and serve up a nice little pdf for you.

Make it pretty with some css and background images and you’re set.
I took a look at the Reportlab api and see some cool canvas capabilities so I’m going to be hacking on that later in the week to try and generate pdf’s without the interim html step with complete graphical layouts.

Hopefully this helps someone needing pdf capabilities in their Django apps. It really is a Pisa cake. (bad pun intended)

Emacs Buffer to OmniFocus

In messing around with emacs early this morning and a little google search I turned up a nice elisp snippet that works well for sending the current buffer you’re working in to OmniFocus with a note attached.


(defun sendOmni () 
  (interactive)
  (let ((fname (buffer-file-name (current-buffer))))
  (do-applescript (concat "tell front document of application \"OmniFocus\" 
  set aTask to (make new inbox task with properties {name:\"From Emacs " 
  (buffer-name (current-buffer)) "\", note:\"file:///" fname "  \" })
      tell note of aTask
        make new file attachment with properties {file name:\"" fname "\"}
      end tell
   end tell"))
	))
(global-set-key [f3] 'sendOmni)

I will be reworking it to my own liking to make it more readable in the OmniFocus inbox and I’m trying to get a recursive script working to send commented TODO’s into inbox items.

OmniFocus Starts, Things Benched

With all the options in great Mac software these days, I’m sure I am not the only one who feels a little disorganized by the organization options presented to us.

I started GTD back in the days of Kinkless GTD. I was then a beta user of OmniFocus and I have been bouncing back and forth between Things and OmniFocus since Things reared it’s pretty little head. Not anymore, I’m done with Things.

Things (Almost)

Things is a beautiful application; enough said about that. It’s simple and streamlined which works well in most situations. However, my life is not even close to simple these days.

Things doesn’t give me the options to easily split projects into sub-projects the way OmniFocus does.

Things leaves it’s waste of finished tasks in plain site. That’s not what I want to stay focused and is probably just a personal preference.

Capturing data from other sources (mail, safari, emacs) is not so straight forward. It requires too many clicks to get the job done. I do know that there are some applescripts floating around to help in this area but it’s not the solution I am looking for.

Things doesn’t have a great start date – finish date scheduling system.

These are the Things that has me starting Omnifocus.

OmniFocus (Win)

The three reasons OmniFocus is my starting player are:

OmniFocus Perspectives are fantastic for organizing your workload once you get the hang of it. I didn’t really get Perspectives until Fraser Speirs explained his workflow. This alone is what initially brought me back to OmniFocus. I mimicked Fraser’s Perspective setup but made a few changes. The biggest being I use flagged as a “Today” list. What I plan to work on today gets a flag status.

Easy capture of data with Clip-O-Tron. Kinda a wierd name but it does what it does so well. I’ve mapped the shortcut to Command+5 and can dump anything in my inbox from Anywhere. That’s priceless.

Syncing OmniFocus with my iPhone is painless. I don’t have to be in my studio to do a sync. Things only syncs over your local wireless network. While I don’t get out of my Studio too often, when I do I want to be able to sync up with my lists.

NOTE: This is not meant to be a review of Things or OmniFocus, just a brain dump of the reasons I’ve settled on OmniFocus to keep me on track with my work and life.

Entomology and Macro Photography

Wikipedia defines entomology as “that which is cut in pieces or engraved/segmented”, or “the scientific study of insects”. I don’t claim to be a entomologist, nor do I cut the little guys into pieces but I do like to get out with my macro gear and teach myself something about nature, below my natural line of sight.

John Deere

There’s a lot of enjoyment in finding a landscape shot that make an impact on you and your peers. It’s addicting and challenging in its own right. But there’s also another world out there that most of us, photographers or not, allow to go unnoticed.

Baby Frog

[Tiny Frog: Roughly 1/4" in length]

I shoot my macro photography with my Nikon D80 and a Tamron 90mm macro. To get uberclose, I will stack Phoenix extension tubes and I always use strobes, usually two. A Nikon SB600 and a Nikon SB26, one on the shoe and one hand-held.

h3. A Story of Discovery

A few months back, a neighbor’s little girl was playing with a home-made aquarium filled with creek water and sediment that was home to a crayfish. In order to show off her crayfish to the crowd it was easier to dump the aquarium on the sidewalk instead of chancing a pinch or two from the “little lobster”. While we watched the crayfish I noticed a tiny pebble start to walk away. Not only was it odd, but the pebble was about 3/16 of an inch in length; impossible to determine what was happening. In order to figure out what was making the rock walk, I broke out the camera gear and used the macro lens and tubes as a microscope. I was able to lure the little creature out of what I thought was a pebble.

Caddisfly Larva

[Caddisfly Larvae: 3/16" long]

I got off about half a dozen shots and still had no idea what this thing was until Graeme Mathieson was kind enough to have a relative of his identify it for me through a Twitter conversation. Turns out that it was a Caddisfly Larvae in it’s early stages. If you’re still unaware of what a Caddisfly is, it’s what fly fisherman model their flys from.

You can see my entire set of this tiny creature in my Flickr stream. Sorry that my glass was a little dusty at the time but I wasn’t planning on shooting anything so I didn’t take the time to clean.

My case in point is simple. Pay attention to what’s going on around you, high and low. You might just learn something new and might get a little enjoyment out of the experience.

Anything Is Quicksilver for Emacs

Prior to my new Macbook Pro, I was an avid Quicksilver user. These days I use Spotlight exclusively. I was exuberant to find a similar solution for Emacs. The past few days I’ve been using Anything.el and Anything-Config.el and it has made my Emacs life much easier. It does things I couldn’t achieve with Vim and using the two together is like Quicksilver for emacs.
Go get the sources I linked to above and add them to your Emacs path. Enter M-x anything [RET] and you will be prompted for a string to search, just like quicksilver. Using your arrow keys will navigate the results, tab gives you options to act on the result. Dive into the source for Anything-Config and you will see it extends the keyboard mappings for Anything giving you many more options.

I’ve found it extremely useful for searching files, launching a project in Dired and searching python tags; and I’m only a few days into it’s feature set.

There’s a very active community making some nice extensions and also a pretty nice looking plugin api for Anything.

I’ll try to do a screencast this weekend to show what Anything can do. No promises since I don’t consider myself good with them like some people I know.

Sandboxing Django Reusable Apps

A couple days ago Brian Rosner posted a great article on Reusable App Conventions. If you haven’t read it yet it’s worth a read or two. I have a few in the works and want to quickly discuss sandboxing your development process for reusables using Pinax.

Sandboxing

A few weeks ago we released Pinax 0.5.0 and while it’s purpose is much more than sandboxing, the project structure is perfect for it. Pinax comes out of the box with two projects. Basic and complete. The basic project only has a few apps for notifications, account, mailers and so forth. Complete project has everything you need for a complete site.

What I have been doing, and I know Brian, Janis and James have been doing the same, is using the basic project for sandboxing development of other projects.

The Simplicity

Grab a copy of Pinax 0.5.0 and un-tar it.
If you have your reusable app project started, add it to your python path and open settings.py located in pinax-0.5.0/projects/basic_project/ and add your reusable app to the INSTALLED_APPS. Now you can ./manage.py syncb and ./manage.py runserver.

I also add Django debug toolar to all my projects as I’m developing them. It is almost an addictive game of reducing queries when using it.

Now go write and test your app as you develop; make changes to the reusable your building while testing it in Pinax. This should not replace writing tests but is a great way of testing your apps for issues that may arise and to see first-hand how they play with other reusable apps in a stable project.

For some good test-related posts — see Eric Holscher.

Twitter From Emacs and Other Useful Finds

I had planned on posting the Python Emacs article for the series but am very short on time today (and probably tomorrow as well). To keep up with the masses, I do have a few short emacs finds I’d like to share.

Twitter from Emacs

This really does go against my article about Distraction Free Programming but aren’t we allowed a little fun now and then?

In the tiny bit of spare time I’ve had this week I’ve been playing around with a few twitter modes for emacs and found one that I feel is simple and works quite well.

Download Twitter.el and add the following to your .emacs configs.


(require 'twitter)
(autoload 'twitter-get-friends-timeline "twitter" nil t)
(autoload 'twitter-status-edit "twitter" nil t)
(global-set-key "\C-xt" 'twitter-get-friends-timeline)
(add-hook 'twitter-status-edit-mode-hook 'longlines-mode)

Initiate M-x customize-group RET twitter RET to enter the configuration settings for twitter where you can enter your username and password. It’s up to you if you want to have emacs save this to your configs or not.

Once that’s done simply use the command C-x t to get your statuses and use M-x twitter-status-edit RET to enter the mode for adding your status. When done, C-c C-c will publish your nerdiness to twitter.

Configure emacs to play nicely with Transmit Remote Editing.

This has been bugging me. I could not edit Transmit remote files until tonight. Click over to find the fix that my friend Justin Lilly found. Thanks Justin!!

Pysmell — And not just for Emacs

PySmell is a python IDE completion helper in development by Orestis Markou.

It tries to statically analyze Python source code, without executing it, and generates information about a project’s structure that IDE tools can use.

There is currently support for Vim, Emacs and TextMate. I’m running Pysmell through some testing and may be including it in the Python article for the Emacs Series. I like what I see so far and look forward to contributing to this project. Thanks Orestis!

Make sure you also check out the other guys who are participating in NaNoWriMoDjango. Eric Florenzano, Eric Holscher, Brian Rosner, Justin Lilly, James Tauber and Janis Leidel.

Emacs Terminal Emulator

In Distraction Free Progamming with Emacs I mentioned the ability to have a shell or terminal running in a window within your workspace. This is extremely handy to run tests in Python Shell or to see when something is going wrong with your code. The emacs wiki is a great source of information but I’ll give you a quick rundown on how to get up and running quickly.

First thing I did was I made sure I could make use of my bash aliases within shell or terminal inside emacs. Since .bash_profile is executed for login shells and .bashrc is executed for interactive non-login shells I made a change to my bash files. I moved all my aliases from .bash_profile to .bashrc and added the following snippet to my .bash_profile to ensure that both terminal and shell are setup and ready to go.


if [ -f ~/.bashrc ]; then
    source ~/.bashrc
fi

When I use terminal within emacs I like to split the frame into multiple windows using C-x 2 for a horizontal split or C-x 3 for a vertical split and resize my windows for a small terminal session, usually in a corner—away from my work. To start the terminal session simply use the key combination M-x term and if you want to use /bin/bash for your session confirm when prompted or you can change it to your liking (tcsh users). To jump to another window simply execute C-x o or even simpler, use your mouse.

[Note: if you prefer shell, use M-x shell instead of term.]

A minor modes that makes my terminal use a little nicer is multi-term which allows me to start multiple terminal sessions with the key combo M-x multi-term, and allow you to page through them with M-x multi-term-next and M-x multi-term-previous. M-x multi-term-list will give you a listing of all your terminal session to choose from. To use multi-term download the minor mode and add the following to your .emacs.


(require 'multi-term)
(multi-term-keystroke-setup) 
(setq multi-term-program "/bin/bash") 

The multi-term-program flag above stops the annoying prompt for /bin/bash everytime I initiate a terminal session.

Now this is distraction free programming. Never having to jump between an editor and terminal!

Portable .bash_profile via TextExpander

I’m taking a short hiatus from the Emacs Series for a stupid hack that actually works quite well for me.

Alias are great for quickly getting things done in terminal but the bad side is I quickly forget the true commands, especially long ones. I spend a lot of time using ssh for my sites and client sites some of which I have no control over the server configuration and .bash_profile or .bashrc for my aliases.

Today I decided to give TextExpander a try as an alias-hack. I created some snippets from a few of my commonly used commands for clearing .pyc files from Django projects to SVN and GIT commands. Enter the shortcuts into terminal when I’m connected to another server and I have mimicked my alias effectively.

I’ve copied some useful aliases from my .bashrc for use in secure shell. It’s probably a good idea to prefix the shortcut with another letter or your TextExpander shortcuts will over-ride your bash aliases when on your local machine. If there’s a way to take advantage of your bash aliases on a server you have NO control over, I’m open to suggestions and willing to learn a new trick.

Distraction Free Programming With GNU Emacs

Editors

Since becoming a switcher in 2004 I exclusively did my work in Textmate. Early summer 2008 I started to explore other options. I spent a couple of months in Vim, MacVim to be precise, and really enjoyed it. After I got comfortable with MacVim, it’s tabs and use of NerdTree for file management started to feel a lot like Textmate. That’s not necessarily a bad thing, just not what I was really looking for.
h3. emacs

During my Vim use, I launched emacs (Carbon Emacs) a few times and was turned off by the key combinations. However, the more I played with it, the more I liked it and the key combos quickly became a non-issue; almost second nature. If i wanted to cheat, i can turn on mac-key-mode for shortcuts that behave like Mac programs. Emacs runs on windows and linux so I decided to take the plunge and learn key combos the emacs way in case I have to jump to Ubuntu.

A Distraction Free Work Environment

For distraction-prone people like me, emacs excels in the full-screen department. When I think full screen I think Writeroom, Aperture and Lightroom, where everything is gone including the menu bar leaving me with nothing except the task I’m working on. This is something I could not effectively do with Textmate and I found myself constantly switching between Textmate and Terminal to get my work done, with an occasional jump to Twitterific, NetNewsWire and irc.

emacs-fullscreen-clean-th.png

[Full-screen capture: this is all i see when I’m working in emacs.]

emacs-fullscreen-menu-th.png

[Full-screen: mouse-over menu bar]

emacs-fullscreen-alt-th.png

[Full-screen: alternate layout]

Explanation of screenshots

Windows in emacs are backwards from what you expect them to be. Emacs calls the collection of windows or a single window a frame and a frame can be split horizontally or vertically in a number of ways to create multiple windows. Depicted in the screenshots I have everything I need. The top window is the code I’m currently working on. In the lower left window I have dired for my file management and terminal (or shell) in the lower right so I never have to switch between emacs and Terminal. The third screenshot is simply a illustration of another way I find myself splitting the frame.

Snippet for full screen toggling

I have my full screen toggle tied to the key combo Meta-[RET]. That’s command+return on a mac. To use this add the following to your .emacs file and restart or refresh emacs.


;; full screen toggle using command+[RET]
(defun toggle-fullscreen () 
  (interactive) 
  (set-frame-parameter nil 'fullscreen (if (frame-parameter nil 'fullscreen) 
                                           nil 
                                           'fullboth)))
(global-set-key [(meta return)] 'toggle-fullscreen) 

In the coming posts in this emacs series I’ll break down dired and the use of shell (or terminal) and how to use these tools effectively.

[Update: i’ve made my dotemacs available in case anyone wants to take a peek. Suggestions are welcome]