Skip to content

Archive

Category: Software

Say you are travelling, or are at a neighbourhood coffee shop, using whatever unsecured WiFi network they make available. You could either:

  1. trust that no one is sniffing your web traffic, capturing passwords, e-mails, IMs, etc.
  2. trust that no one is using more sophisticated methods to trick you into thinking that you are secure (i.e. man in the middle attack)
  3. route your Internet traffic through a secure tunnel to your home PC before going out onto the web, protecting you from everyone at your current location

which would you choose?

VPNs and SSH tunnels are actually a relatively easy means for you to be more secure while browsing the Internet from potentially dangerous locations. There are many, many different ways for you to do this but I find using a Linux PC that is running on your home network to be the easiest.

  1. Configure your home Linux PC. Install ssh (and sshd if it is separate). If you are using Ubuntu this is as easy as running the following command: sudo apt-get install ssh
  2. Sign up for a free DNS service like DynDNS so that you know of a web address that always points to your home Internet connection. To do this follow the instructions at the service you choose.
  3. On your laptop (that you have taken with you to the hotel or coffee shop) connect to your home PC’s ssh server. If you are on Windows you will need to get a program like PuTTY. See their documentation on how to forward ports. On Linux you can simply use the ssh command. The goal is to forward a dynamic port to the remote ssh server. For instance if you are using a Linux laptop and ssh then the command would look something like: ssh -D [dynamic port] [user]@[home server] -p [external port number - if not 22]. An example of one would be ssh -D 4096 user@example.com -p 4000
  4. In your browser open the networking options window. This will allow you to tell the browser to forward all of its traffic to a proxy, which in this case, will be our dynamic port that we set up in step 3. Here is an example of my configuration for the example above.
  5. Browse normally.

You are now browsing the Internet by routing all of your traffic (in Firefox) securely through your home PC. Note that this doesn’t actually make web browsing any more secure beyond protecting you from people in your immediate vicinity (i.e. connected to the same insecure WiFi network).

I logged onto my desktop the other day, for the first time in a couple of weeks – I’ve been away travelling, and was surprised to notice that my PGP key was set to expire. Long story short I have generated a brand new key.

OpenPGP Key

Name: Tyler Burton
Key ID: 0x1CD3E3D8
Key Fingerprint: 96ED 6B13 10B1 69C1 8299 693C 2921 6D80 1CD3 E3D8
Keyserver: pgp.mit.edu
Key Algorithm: RSA
Preferred Cipher: AES256
Preferred Digest: SHA512
Direct Download: Download Here

There has been quite a bit of activity on The Linux Experiment over the past little while. Check out the site here or quickly jump to the post that I wrote below.

Big distributions, little RAM 3

How do the ‘big time’ distributions handle on constrained hardware? Take a look.

How to install sun-java6-jdk and Netbeans in Ubuntu 11.10

A simple process to install the official SunOracle Java JDK and Netbeans IDE in the latest Ubuntu.

Ubuntu 11.10′s WiFi crashes my router

The new Ubuntu release is pretty good. Unfortunately it also causes my router to crash.

Gentoo (A.K.A. “Compiling!”)

My first post for the second Linux Experiment where I speak about my Gentoo first impressions.

How to enable reboot/shutdown in KDE on Gentoo

Closed source AMD/ATI drivers, wireless networking and Flash in Gentoo

How to update your (whole) Gentoo system

A trio of small posts that walk new Gentoo users through setting up and doing some basic things in their new desktop.

How to play Red Alert 2 on Linux

I managed to get this classic game to run great on Linux. It even includes a bit of a hack that allows you to play LAN games. I don’t think you can even do that on Windows any more.

Oh Gentoo

My final post of the second Linux Experiment. Includes my conclusions on running Gentoo as a day-to-day desktop system.

In case you somehow found your way here and haven’t already seen them over at The Linux Experiment, I have put up two new posts that deal with fixes for your linux desktop.

Two monitors. Different resolutions. One desktop.

If you’ve ever wondered how to use two monitors with different resolutions as a single, unified, extended desktop I highly suggest you do a quick read of this post. I’ve covered how to avoid, and fix, the ‘dead space’ issue where application windows can get lost because of the difference is vertical resolutions.

Fix PulseAudio loopback delay

For some reason I encountered an issue where the PulseAudio loopback module introduced a delay in my sound, causing audio and video to be out of sync. Here is a simple solution to fix the issue.

 

Hopefully the above two posts can be of use to some of you out there. Let me know if you have any issues getting them to work.

A short post but I figured I would throw it up here before I lose my code. There are a couple of different ways that you can load jar’d code at runtime but here is a simple solution that I found to work very easily.

       File myJar = new File("myJar.jar");
       URL url = myJar.toURI().toURL();

       Class[] parameters = new Class[]{URL.class};

        URLClassLoader sysLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class sysClass = URLClassLoader.class;
        try
        {
            Method method = sysClass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysLoader,new Object[]{ url });

            Constructor cs = ClassLoader.getSystemClassLoader().loadClass("com.example.MyClass").getConstructor();
            MyInterface instance = (MyInterface)cs.newInstance();
            instance.someFunction();
        }
        catch(Exception ex)
        {
            System.err.println(ex.getMessage());
        }

In the code example above the jar at the location pointed to by the url object is dynamically loaded and an instance of the class com.example.MyClass is created that conforms to a known interface MyInterface. This could be used in a situation where you are loading plugins that use a common interface example.

For something to do I decided to see if I could create a very simple Java media player. After doing some research, and finding out that the Java Media Framework was no longer in development, I decided to settle on GStreamer to power my media player.

GStreamer for the uninitiated is a very powerful multimedia framework that offers both low-level pipeline building as well as high-level playback abstraction. What’s nice about GStreamer, besides being completely open source, is that it presents a unified API no matter what type of file it is playing. For instance if the user only has the free, high quality GStreamer codecs installed, referred to as the good plugins, then the API will only play those files. If however the user installs the other plugins as well, be it the bad or ugly sets, the API remains the same and thus you don’t need to update your code. Unfortunately being a C library this approach does have some drawbacks, notably the need to include the JNA jar as well as the system specific libraries. This approach can be considered similar to how SWT works.

Setup

Assuming that you already have a Java development environment, the first thing you’ll need is to install GStreamer. On Linux odds are you already have it, unless you are running a rather stripped down distro or don’t have many media players installed (both Rhythmbox and Banshee use GStreamer). If you don’t it should be pretty straight forward to install along with your choice of plugins. On Windows you’ll need to head over to ossbuild where they have downloadable installers.

The second thing you’ll need is gstreamer-java which you can grab over at their website here. You’ll need to download both gstreamer-java-1.4.jar and jna-3.2.4.jar. Both might contain some extra files that you probably don’t need and can prune out later if you’d like. Setup your development environment so that both of these jar files are in your build path.

Simple playback

GStreamer offers highly abstracted playback engines called PlayBins. This is what we will use to actually play our files. Here is a very simple code example that demonstrates how to actually make use of a PlayBin:

public static void main(String[] args) {
     args = Gst.init("MyMediaPlayer", args);

     Playbin playbin = new PlayBin("AudioPlayer");
     playbin.setVideoSink(ElementFactory.make("fakesink", "videosink"));
     playbin.setInputFile("song.mp3");

     playbin.setState(State.PLAYING);
     Gst.main();
     playbin.setState(State.NULL);
}

So what does it all mean?

public static void main(String[] args) {
     args = Gst.init("MyMediaPlayer", args);

The above line takes the incoming command line arguments and passes them to the Gst.init function and returns a new set of arguments. If you have ever done any GTK+ programming before this should be instantly recognizable to you. Essentially what GStreamer is doing is grabbing, and removing, any GStreamer specific arguments before your program will actually process them.

     Playbin playbin = new PlayBin("AudioPlayer");
     playbin.setVideoSink(ElementFactory.make("fakesink", "videosink"));
     playbin.setInputFile("song.mp3");

The first line of code requests a standard “AudioPlayer” PlayBin. This PlayBin is built right into GStreamer and automatically sets up a default pipeline for you. Essentially this lets us avoid all of the low-level craziness that we would have to normally deal with if we were starting from scratch.

The next line sets the PlayBin’s VideoSink, think of sinks as output locations, to a “fakesink” or null sink. The reason we do this is because PlayBin’s can play both audio and video. For the purposes of this player we only want audio playback so we automatically redirect all video output to the “fakesink”.

The last line is pretty straight forward and just tells GStreamer what file to play.

     playbin.setState(State.PLAYING);
     Gst.main();
     playbin.setState(State.NULL);

Finally with the above lines of code we tell the PlayBin to actually start playing and then enter the GStreamer main loop. This loop continues for the duration. The last line is used to reset the PlayBin state and do some cleanup.

Bundle it with a quick GUI

To make it a little more friendly I wrote a very quick GUI to wrap all of the functionality with. The download links for that (binary only package), as well as the source (all package) is below. And there you have it: a very simple cross-platform media player that will playback pretty much anything you throw at it.

Binary Only Package All Package
File name: my_media_player_binary.zip my_media_player_all.zip
File hashes: Download Here
GPG signature: Download Here Download Here
Screenshots:
Version: March 13, 2011
File size: 1.5MB 1.51MB
File download: Download Here Download Here

With no real alternative to Xcode on non-Mac platforms there is a real lack of a genuine development environment for Objective-C. With projects like GNUstep picking up the Objective-C runtime portion of the equation I’ve decided to try my hand at filling the other gap by creating a very simple IDE strictly for Objective-C. My goals were simple: create a basic IDE written in Objective-C that provides syntax highlighting, one button program compilation, and (if I could get it to work) some form of auto-complete or a suggestion system.

For my project I decided to target the cross-platform GTK+ because while Objective-C has the AppKit GUI libraries they just don’t look native enough for my liking. In addition because Objective-C is backwards compatible with all C code I could easily embed the GTK+ calls within wrapped objects and methods.

With a simple press of a button the program is compiled and run in the terminal just as you would expect.

As you can see I’ve so far succeeded in my simple goals. Although this project is still very much a work in progress I do hope to be able to release the source to it once I get it to a point where it is cleaned up and feature complete.

The iOS platform, consisting of the iPhone and the iPad, has seen most of it’s success thanks to the plethora of applications (apps) available for download. It is without a doubt the platform’s strongest asset and one that, thanks to the continued success of apps like Angry Birds, seems likely to continue for some time. While a lot of time on these devices is spent listening to music, browsing the web, reading e-mails and, let’s face it, playing games I wanted to write up a quick post about some of the other apps that I use on a regular basis. These small, often single purpose, programs make my life easier in their unique way and keep me connected no matter where I am. The following is a list of apps, ordered by how often I use them, that I am currently making heavy use of on my iPhone.

10. VLC

The iOS media player can play a large number of audio and video formats. Unfortunately there are still a few obscure formats, and some that Apple just doesn’t like, that won’t work. This is where VLC comes in. Like the desktop counterpart, VLC lets the device play almost every file type imaginable, from MKV to OGG. It even integrates into the e-mail client letting me view attachments that I otherwise wouldn’t have been able to. The only drawback is the ridiculous way you have to add media to the VLC library. Sadly this is on Apple’s side of the equation and I doubt we’ll see this changed anytime soon.

Do I have to read a manual first too?

9. IMDb

The Internet Movie Database is an awesome website that tracks almost ever detail of a movie’s production (from actors to directors and more). This app is the iOS version of their website (they actually block you from using the proper website on your device). Thankfully this is also one of the most well designed and easy to use apps I have ever seen. Need to find the name of that actress? No problem. Want to know what else she’s been in? Super simple. This app is a staple that everyone should have installed.

It even gives you movie news and showtimes

8. Corus Radio

There are a number of streaming radio apps available for download from Shoutcast! to those specific to a certain radio station. Corus Radio is one such application. It makes it easy to listen to any of the Corus owned radio stations all from within a single app. From a design perspective this is not a very good app, but its no frills approach makes it sufficient for me when I want to catch the early morning Dean Blundell Show.

No frills but it does the job

7. Convert Units

Have you ever been reading a recipe or following directions and had to convert between oz and mL or lbs and kg? Enter Convert Units. This super handy application lets you easily convert between all sorts of different units for all kinds of situations

Did you know 1 beer = 0.355L?

Convert Units works in all sorts of different situations

6. Netflix

With the recent release of Netflix in Canada I am suddenly able to try out this service from the comfort of my… phone. OK so maybe it’s not the best way to watch movies but it’s still really cool. There isn’t much to really say about this beyond the fact that this is yet another excellent Netflix experience.

I wonder how much data a movie uses over 3G

5. Facebook

Ah Facebook. Whatever your feelings are about this privacy eroding service that enables complete publication of your life you to keep in touch with friends and family, Facebook (the app) is a prime example of how an iOS program should work. It is so simple and feature rich (a rare combination) that I actually prefer it to the full website.

Even better than their excellent mobile site

4. Newsy

Newsy is an interesting app, actually more of a front end to their website, that combines various perspectives of a newsworthy event from different TV news shows, blogs and radio commentators. Their tag-line is “Multiple sources. The real story.” and one that I believe they live up to. If you are looking for a more or less non-bias summary of something in the news I would highly recommend checking out Newsy.

Top stories of the day (videos and transcripts)

3. TweetDeck

There are literally dozens, maybe even hundreds, of Twitter clients for iOS but none are as fully featured (in my opinion at least) as TweetDeck. Taking a cue from their desktop version, this client displays all of the information in a series of columns that you can swipe back and forth to cycle through.

Everything is split up into customizable columns

If you do use the desktop version as well it will automatically sync things between them so you don’t have to constantly update both independently. My only complaints have to do with the lack of real multitasking and the crash happy nature of the in-application browser. Honestly I don’t know how they did it… but they took the perfectly stable browser component and broke it.

2. PingChat!

PingChat! has the dubious honour of being one of the only remaining cross-platform instant messengers in the vein of BlackBerry Messenger. This means that from your iOS device can talk to your friend on an Android device or even on a BlackBerry.

PingChat! also supports group chat

Like BBM, PingChat! shows you when the other party has received a message and runs over the data network, thus saving you from text messaging fees. Another nice feature is the ability to send pictures, video, audio, contact information and more.

The send contact feature is especially useful for quickly sharing information

I highly recommend this application, and not just because the guys behind it are local ;)

1. IM+

iOS has a slew of instant messenger applications but I prefer IM+ to all of the other ones that I’ve tried. A slick interface, tons of features, and a quick update cycle means that this app is constantly improving.

Trust me, it looks better without all of the censorship ;)

You can send pictures, audio, and videos to your contacts, talk on all different types of services (MSN, AOL, etc.) and even configure it to stay logged in on their servers so that (even with the application closed) you get Push notifications when someone messages you. Overall it offers a solid experience that is only getting better and better.

Honourable Mention

Epic has recently released a tech demo called Citadel showcasing the Unreal Engine running on iOS. This is by far the best example of what the iPhone/iPad hardware is capable of in terms of delivering absolutely stunning graphics. Sadly that’s all it is, a tech demo. Hopefully we will see this technology used more often going forward.

Very gorgeous graphics

As sort of follow-up-in-spirit to my older post I decided to share a really straight forward way to use Objective-C to build GTK+ applications.

Objective-what?

Objective-C is an improvement to the iconic C programming language that remains backwards compatible while adding many new and interesting features. Chief among these additions is syntax for real objects (and thus object-oriented programming). Popularized by NeXT and eventually Apple, Objective-C is most commonly seen in development for Apple OSX and iOS based platforms. It ships with or without a large standard library (sometimes referred to as the Foundation Kit library) that makes it very easy for developers to quickly create fast and efficient programs. The result is a language that compiles down to binary, requires no virtual machines (just a runtime library), and achieves performance comparable to C and C++.

Marrying Objective-C with GTK+

Normally when writing a GTK+ application the language (or a library) will supply you with bindings that let you create GUIs in a way native to that language. So for instance in C++ you would create GTK+ objects, whereas in C you would create structures or ask functions for pointers back to the objects. Unfortunately while there used to exist a couple of different Objective-C bindings for GTK+, all of them are quite out of date. So instead we are going to rely on the fact that Objective-C is backwards compatible with C to get our program to work.

What you need to start

I’m going to assume that Ubuntu will be our operating system for development. To ensure that we have what we need to compile the programs, just install the following packages:

  1. gnustep-core-devel
  2. libgtk2.0-dev

As you can see from the list above we will be using GNUstep as our Objective-C library of choice.

Setting it all up

In order to make this work we will be creating two Objective-C classes, one that will house our GTK+ window and another that will actually start our program. I’m going to call my GTK+ object MainWindow and create the two necessary files: MainWindow.h and MainWindow.m. Finally I will create a main.m that will start the program and clean it up after it is done.

Let me apologize here for the poor code formatting; apparently WordPress likes to destroy whatever I try and do to make it better. If you want properly indented code please see the download link below.

MainWindow.h

In the MainWindow.h file put the following code:

#import <gtk/gtk.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

//A pointer to this object (set on init) so C functions can call
//Objective-C functions
id myMainWindow;

/*
* This class is responsible for initializing the GTK render loop
* as well as setting up the GUI for the user. It also handles all GTK
* callbacks for the winMain GtkWindow.
*/
@interface MainWindow : NSObject
{
//The main GtkWindow
GtkWidget *winMain;
GtkWidget *button;
}

/*
* Constructs the object and initializes GTK and the GUI for the
* application.
*
* *********************************************************************
* Input
* *********************************************************************
* argc (int *):    A pointer to the arg count variable that was passed
*             in at the application start. It will be returned
*            with the count of the modified argv array.
* argv (char *[]):     A pointer to the argument array that was passed in
*            at the application start. It will be returned with
*            the GTK arguments removed.
*
* *********************************************************************
* Returns
* *********************************************************************
* MainWindow (id):    The constructed object or nil
* arc (int *):        The modified input int as described above
* argv (char *[]):    The modified input array modified as described above
*/
-(id)initWithArgCount:(int *)argc andArgVals:(char *[])argv;

/*
* Frees the Gtk widgets that we have control over
*/
-(void)destroyWidget;

/*
* Starts and hands off execution to the GTK main loop
*/
-(void)startGtkMainLoop;

/*
* Example Objective-C function that prints some output
*/
-(void)printSomething;

/*
********************************************************
* C callback functions
********************************************************
*/

/*
* Called when the user closes the window
*/
void on_MainWindow_destroy(GtkObject *object, gpointer user_data);

/*
* Called when the user presses the button
*/
void on_btnPushMe_clicked(GtkObject *object, gpointer user_data);

@end

MainWindow.m

For the class’ actual code file fill it in as show below. This class will create a GTK+ window with a single button and will react to both the user pressing the button, and closing the window.

#import “MainWindow.h”

/*
* For documentation see MainWindow.h
*/

@implementation MainWindow

-(id)initWithArgCount:(int *)argc andArgVals:(char *[])argv
{
//call parent class’ init
if (self = [super init]) {

//setup the window
winMain = gtk_window_new (GTK_WINDOW_TOPLEVEL);

gtk_window_set_title (GTK_WINDOW (winMain), “Hello World”);
gtk_window_set_default_size(GTK_WINDOW(winMain), 230, 150);

//setup the button
button = gtk_button_new_with_label (“Push me!”);

gtk_container_add (GTK_CONTAINER (winMain), button);

//connect the signals
g_signal_connect (winMain, “destroy”, G_CALLBACK (on_MainWindow_destroy), NULL);
g_signal_connect (button, “clicked”, G_CALLBACK (on_btnPushMe_clicked), NULL);

//force show all
gtk_widget_show_all(winMain);
}

//assign C-compatible pointer
myMainWindow = self;

//return pointer to this object
return self;
}

-(void)startGtkMainLoop
{
//start gtk loop
gtk_main();
}

-(void)printSomething{
NSLog(@”Printed from Objective-C’s NSLog function.”);
printf(“Also printed from standard printf function.\n”);
}

-(void)destroyWidget{

myMainWindow = NULL;

if(GTK_IS_WIDGET (button))
{
//clean up the button
gtk_widget_destroy(button);
}

if(GTK_IS_WIDGET (winMain))
{
//clean up the main window
gtk_widget_destroy(winMain);
}
}

-(void)dealloc{
[self destroyWidget];

[super dealloc];
}

void on_MainWindow_destroy(GtkObject *object, gpointer user_data)
{
//exit the main loop
gtk_main_quit();
}

void on_btnPushMe_clicked(GtkObject *object, gpointer user_data)
{
printf(“Button was clicked\n”);

//call Objective-C function from C function using global object pointer
[myMainWindow printSomething];
}

@end

main.m

To finish I will write a main file and function that creates the MainWindow object and eventually cleans it up. Objective-C (1.0) does not support automatic garbage collection so it is important that we don’t forget to clean up after ourselves.

#import “MainWindow.h”
#import <Foundation/NSAutoreleasePool.h>

int main(int argc, char *argv[]) {

//create an AutoreleasePool
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//init gtk engine
gtk_init(&argc, &argv);

//set up GUI
MainWindow *mainWindow = [[MainWindow alloc] initWithArgCount:&argc andArgVals:argv];

//begin the GTK loop
[mainWindow startGtkMainLoop];

//free the GUI
[mainWindow release];

//drain the pool
[pool release];

//exit application
return 0;
}

Compiling it all together

Use the following command to compile the program. This will automatically include all .m files in the current directory so be careful when and where you run this.

gcc `pkg-config –cflags –libs gtk+-2.0` -lgnustep-base -fconstant-string-class=NSConstantString -o “./myprogram” $(find . -name ‘*.m’) -I /usr/include/GNUstep/ -L /usr/lib/GNUstep/ -std=c99 -O3

Once complete you will notice a new executable in the directory called myprogram. Start this program and you will see our GTK+ window in action.

If you run it from the command line you can see the output that we coded when the button is pushed.

Wrapping it up

There you have it. We now have a program that is written in Objective-C, using C’s native GTK+ ‘bindings’ for the GUI, that can call both regular C and Objective-C functions and code. In addition, thanks to the porting of both GTK+ and GNUstep to Windows, this same code will also produce a cross-platform application that works on both Mac OSX and Windows.

Source Code Downloads

Source Only Package
File name: objective_c_gtk_source.zip
File hashes: Download Here
File size: 2.4KB
File download: Download Here

Recently I have been messing around with Django, a very cool Python powered web framework that makes it very easy to create websites quickly. Like similar frameworks (i.e. Ruby on Rails, CakePHP, etc.) Django excels at doing most of the heavy lifting for you. What is most jarring at first, and perhaps the most powerful design choice later on, is that Django has an almost complete separation of server side code from website design.

How does it work?

Django works in a very straightforward way.

  1. Upon receiving a new request, Django will match the request to a handler function.
  2. The handler function will gather all of the data needed to display the page as well as do any server-side changes (i.e. database updates or whatever).
  3. The handler function will pass the information to the HTML template to render and the result will be sent back to the requester.

This very straight forward, three step process is just a high level view of the power that Django offers however.

1. Match incoming requests to an appropriate handler function

This step is actually done by using Django’s urlpatterns system. Essentially a collection of regex this (very fast!) function easily re-directs your incoming requests to their destinations. For instance in the example below a request to www.example.com/ would be handled by the index_handler function, whereas a request to www.example.com/hello/ would be handled by some_other_function.

urlpatterns = patterns('',
     ('^/$', index_handler),
     ('^hello/$',  some_other_function),
)

What’s beautiful about this is that you can easily change the URL structure of your website (or just change URL mappings) without actually moving any code. So unlike something like classical PHP, where the code is embedded in the web page, Django simply looks at the incoming URL and then decides which code it should run. If I want to change my URL syntax from www.example.com/blog/ to www.example.com/awesomeblog/ I can do it (without breaking anything!) by just changing this file. And this is just the start of the cool things you can do with this file. As the official Django tutorial says:

Because the URL patterns are regular expressions, there really is no limit on what you can do with them. And there’s no need to add URL cruft such as .php — unless you have a sick sense of humor, in which case you can do something like this:

(r’^polls/latest\.php$’, ‘polls.views.index’),

But, don’t do that. It’s silly.

2. The handler function

Instead of reinventing the wheel, each handler function is simply a standard Python function that takes in a request object. In its most basic form it looks something like this:

def hello(request):
     return HttpResponse("Hello world")

Of course being standard Python these functions also inherit the ability to do anything Python can do, including using real objects. Django does an excellent job of marrying these objects with the database engine so that, if you want to, you don’t ever have to write any real SQL. Instead Django will handle the creation of highly optimized SQL calls for you automatically when you call basic object functions.

One of the coolest built in features is the Form class. This class represents a standard HTML form as well as a selection of standard rendering formats (i.e. tables, ordered lists, unordered lists, etc.) in addition to allowing you to completely customize them. Why put this HTML in a Python function and not in the HTML template? Because using it here gives us free validation. I’ll give you an example:

class ContactForm(forms.Form):
     subject = forms.CharField()
     email = forms.EmailField(required=False)
     message = forms.CharField()

Creates a form class with three fields (two of which are required). The resulting HTML (depending on how you want it displayed) is something like:

<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>

OK so how is it used?

def contact(request):
     if request.method == 'POST':
          form = ContactForm(request.POST)
          if form.is_valid():
               return HttpResponse("Everything was valid!")
          else:
               form = ContactForm()
               return render_to_response('contact_form.html', {'form': form})

This function will accept the form’s submitted POST arguments, validate them (meaning that at a minimum the subject and message fields need to be filled out) and return a page saying “Everything was valid!”. If the form is not valid it simply hands off the form object to the template engine to be rendered into the html file called “contact_form.html”

3. The template engine

Sticking to its MVC roots Django makes it very easy for web designers to use the data they need without actually needing to write any real code.

For instance here is the example contact_form.html from above:

<html>
  <head>
    <title>Contact us</title>
  </head>
  <body>
    <h1>Contact us</h1>
    <form action="" method="post">
      <table>
        {{ form.as_table }}
      </table>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

The {{ }} braces tell the temple engine to place a Python object in the page at that spot. This is great but what if you need to handle multiple pieces of data (like a Python list)? The template engine allows you access to easy functionality to accomplish anything you can think of. Here is an example of some template ‘code’ that will put all of the items in item_list in an unordered HTML list for displaying.

<ul>
  {% for item in item_list %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

More to come

I know this post sounds a lot like an advertisement but the truth is that the flexibility and power of Django is really stunning. I will definitely be doing some more work in this framework going forward so expect to see more updates sometime in the future.

Useful links: