Upload files from a web browser. Support for old and modern browsers. Dropzone.js and the jquery.iframe-transport.js plugin.

I never thought that writing an upload file form that works for old and modern browsers was so complicated. But unfortunately it was. I will try to put together the things I have learnt in case you are in the same situation.

For modern browsers (those that support file uploads via XMLHttpRequest, hence via Ajax) this task was quite easy because there are many interesting libraries out there. But for old browsers you need to use the standard input file type and it doesn’t allow the client to handle the server response. Since I’m building a rich-client web application I need to handle the response in the client rather than in the server. We will see a workaround to get this done.

I found a fantastic plugin to upload files from my web application: Dropzone.js. Dropzone is a light weight JavaScript library that turns an HTML element into a dropzone. This means that a user can drag and drop a file onto it, and the file gets uploaded to the server via Ajax.

It works quite well and it gives me all I need, BUT Dropzone only works in modern browsers. And I really want my web application to work in most of the browsers.

Let’s give some very basic technology background here. Dropzone uses Ajax to upload files. Ajax is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Ajax depends on XMLHttpRequest. XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script. But, old browsers don’t support file uploads via XMLHttpRequest.

I had, then, to combine the dropzone.js library (for modern browsers) and the basic file upload form used in the olden days (for old browsers) to give support to all browsers. Fortunately Dropzone takes this into account, if the browser is not supported, the dropzone.js library calls automatically a fallback function that by default shows a fallback class that contains an input field and a submit button. You can customize that fallback class and that fallback function.

My intention is not to explain how to make the plugins work in your project but to focus in the compatibility issue. You should already know how Dropzone works.

Modern browsers

This would be the html for my form using Dropzone:

This is how it looks like for modern browsers (I changed the “Drag and drop files here” image for the “Añade una foto” one in spanish):

no columns

You drag and drop files there or click to select them and afterwards you get this:

no columns

Old browsers

When the browser doesn’t allow the upload of files via Ajax, the plugin creates the form below by default:

no columns

You can customize the message that is displayed defining the dictFallbackMessage and dictFallbackText options in the plugin. Also you can write your own fallback form in the html:

The fallback class div will only be displayed when the plugin detects that the browser does not support file upload via Ajax. I have added a spinner to give some feedback to the user while uploading the image in case of slow servers.

Ok, this is great, you now have a nice upload form working for modern browsers and one not so nice but that is working for old browsers. This is correct, but probably the behaviour of the old form is not what we expect.

That basic implementation for uploading files in old browsers doesn’t provide a way of processing the response returned by the server. I’m using Backbone.js for my web application, and I want to load the server response data back into my app so I can show a success message in my page. I need to customize that fallback option provided by Dropzone.js.

How do I get that? There is a workaround that gives the impression of Ajax file uploads (and thus the same workflow and UI from the user’s perspective), without actually submitting the file via XHR. It is known as the iFrame method. You can find a good explanation of it in this blog post by Alfa Jango.

I have followed Esteban Pastorino post for doing this.

There is a plugin that helps you to use the iFrame solution, the jQuery Iframe Transport plugin. This plugin implements an iframe transport so that $.ajax() calls support the uploading of files using standard HTML file input fields. This is done by switching the exchange from XMLHttpRequest to a hidden iframe element containing a form that is submitted.

With this plugin I can now make an Ajax request to the server and process the data returned by the server:

I work in Ubuntu and by default the files are uploaded to the /tmp/ folder.
In the server side I’m working with Node.js and Express.js. In Express you can customize the upload directory with this option:

I know this can be a bit too much to understand with just one reading, but at least I hope it can be useful as a basic approach to the problem of compatibility for uploading files in browswers.

Internet Explorer for Ubuntu

I know the title can cause some misunderstanding. It is not installing Internet Explorer browser in Ubuntu what I plan to do in this post but rather having an Internet Explorer browser in a Virtual Machine without having to install Microsoft Windows.

I came to the point where I needed to test my web platform in different browsers, because it works pretty well in Firefox and Chrome, the browsers that I’m using in my Ubuntu distribution, but what about other browsers? Internet Explorer is the second in the list of Browser usage, we should take care that everything works well there.

I was annoyed thinking I had to install the whole Microsoft Windows operating system in a Virtual Machine to get Internet Explorer in my Ubuntu machine, but I found a better solution. Microsoft provides virtual machine disk images to facilitate website testing in multiple versions of IE. I had to use a Virtual Machine but at least I didn’t have to worry about finding a Microsoft Windows image to install.

I won’t re-write what is perfectly explained here. Thanks a lot to xdissent for it!

I will only add some comments. I got some errors when it tried to install Virtualbox Guest Additions. My workaround was to install the Guest Additions myself:

And then when starting the Virtual Machine, once you are in, press CTRL + D and install the Guest Additions manually.


Mangopay workflow for marketplaces using Node.js wrapper

I’m building a marketplace and I came to the point of integrating a payment tool.

My marketplace is a web application that uses Node.js for the server side, hence I was looking for one tool that already had a Node.js wrapper, I didn’t want to spend time in that. Also I’m based in Europe, this fact reduced drastically the alternatives for a payment tool.

After analyzing many posibilities I went for Mangopay. Mangopay doesn’t have an offical Wrapper for Node.js but I found this one from larafale that it is excellent. I have contributed myself to it with documentation and some methods, so feel free to do the same.

I found hard to understand how Mangopay worked from a functional point of view. My intention with this post is to explain the workflow for making payments in a marketplace. My explanations below will refer to the Mangopay Node.js wrapper based on Mangopay API.

Within Mangopay there are different options to make the payment. I have chosen to create a wallet per each user and transfer the money between wallets instead of creating a escrow wallet for the platform to behave as the intermediate receiver/sender of the transactions. Transferring the money from wallet to wallet without intermediary gives you a better management of the transactions, no problem to know which user needs to be KYC authenticated and no problems to refund. Mangopay says that this is the correct workflow that will avoid any kind of confusion and problems due to KYC or refunds.

First, install Mangopay library:

Then you need to create a mango instance:

Now we are ready to process the payment.

Create a User and a Wallet for the buyer

There is a method in the Node.js wrapper that creates a user and a wallet at the same time.

Mangopay, as an electronic money issue needs to meet some legal obligations in order to fight fraud, money laundering and financing of terrorism. There are different levels of authentications depending on the transaction amount. In my case I only needed light authentication. You can find further information here.

For light authentication you are required to collect from your users email, firstname, lastname, country of residence, birthday and nationality.

The function returns 3 objects: error, user object and wallet object.

The user and wallet objects are JSON objects liket these ones:

We are interested in the user Id (user.Id) and the wallet Id (wallet.Id).

Register a Card for the buyer

To make the payment to the buyer wallet (Direct PayIn) you need to register her card first.

The res object returned is a raw ‘http’ response object.
The card object returned is a JSON object with several fields, we are interested in the CardId field.

Make the payment to the buyer wallet (PayIn)

Here, I should explain some of the fields:

  • AuthorId: buyer User Id
  • CreditedUserId: buyer User Id
  • DebitedFunds: amount taken from the buyer credit card. Amounts are defined in cents.
  • In my case I charge a fee to the buyer so, let’s say that the product costs 100€ and the fee we apply is 10%, I should set the amount debited to 110€ (11000 cents).

  • Fees: your fees taken on the DebitedFunds.
  • In our example, I have said the fees were 10% of the price product, so this field should be set to 10€ (1000 cents).

The fees go to a specific fees wallet created by Mangopay specificly for your platform. At the end of each month Mangopay team withdrawal the fees into your bank acocunt. The amount transferred corresponds to your own collected fees minus MangoPay fees.

We store the PayinId field returned by the method.

When the purchase has been completed and the product has arrived to the buyer we proceed to pay the seller.

Create a User and a Wallet for the seller

See instructions above for creating a user and a wallet for the buyer.

Transfer money between buyer and seller wallet

  • AuthorId: buyer User Id.
  • DebitedWalletID: buyer Wallet Id.
  • CreditedUserId: seller User Id.
  • CreditedWalletID: seller Wallet Id.
  • DebitedFunds: the money taken from the buyer Wallet.
  • In our example the price of the product is 100€, so we are taking those 100€ from the buyer wallet. We set this field to 10000 cents.

  • Fees: Fees taken on the transfer.
  • I apply a fee of 10% to the seller as well. So the Fees field should be set to 10€ (1000 cents).

The seller will receive DebitedFunds – Fees = 90€.

Register a bank account for the seller

Before sending a wire transfer we need to register the bank account.

It returns a JSON file with an Id field, that is the Bank Account Id.

Make a PayOut transfer to the seller bank account

Before I transferred 90€ to the seller wallet (product price – fees). This is the amount that we are transfering from her wallet to her bank account, 9000 cents. I am not charging any fees in this transaction because I did it before.

And this is all for now. I hope this is useful for someone.

Bootstrap 3. Grid system

Bootstrap is a front-end framework that provides components, classes and sets of css for faster and easier web development.

In August 2013 Bootstrap 3 was released and one of its new features was its grid system that allows you to make fast and easy layouts using some predefined classes.

This post is an introduction to Bootstrap grid system explaining its classes and how to use them.

row and col-* classes

The row class is used to create an horizontal group of columns. Inside this row div we place the columns. Every row in the grid is made up of 12 units, we group these units in column classes as desired.

It is easier to understand with examples.

Let’s start adding some paragraphs under a row class without defining any columns. See below the code.

I have highlightened some important lines. In line 7 we import the Bootstrap css file. In line 17 we wrap our components within a .container. Quoting Bootstrap documentation “rows must be placed within a .container for proper alignment and padding”. And in line 21 we define our row class. I have defined some style for the .row, a background color and a border, so it is easy to visualize.

As a result this is the web page that is displayed by the browser:

no columns

Let’s create 4 columns now in our layout:

We have defined 4 same size columns, 3 units each, resulting in a total of 12 units (3+3+3+3), the row size.

no columns

We can have different sizes for columns within the same row:

no columns

Grid sizes: col-xs-*, col-sm-*, col-md-*, col-lg-*

Bootstrap defines different classes based on the screen width, so we can specify different layouts depending on the device type we are using to visualize our web page.

These classes are defined based on Bootstrap media queries that create the following breakpoints:

DeviceScreen widthClass prefix
Extra small devices (Phones)< 768 px.col-xs-
Small devices (Tablets)>= 768 px.col-sm-
Medium devices (Laptops)>= 992 px.col-md-
Large devices (Big monitors)>= 1200 px.col-lg-

The .col-* classes are only applied if the screen width is greater than or equal to the breakpoint size. Imaging you define two columns as .col-md-6 and .col-md-6, in a laptop (screen width > 992px) you will see those 2 columns while in a mobile phone you will see only 1 column since the classes are not applied for screen width lower than those 992 px.

Let’s see an example.

This is what you see in medium and large screens. It is applying .col-md.3.

no columns

In small screens like tablets .col-sm.6 is applied.

no columns

And finally in a mobile phone, none of the .col-* classes are applied, displaying by default 1 column.

no columns

Nesting columns

You can nest rows within existing columns.

no columns


You can specify an offset for a column using col-md-offset-N. With N you specify the number of units you want the column to be moved. This is commonly used for centering columns.

no columns

Space between columns

By default the space between columns, called gutter, is 30 px, a padding of 15px on each side of a column.

We can change this width defining a value for the padding property for the .col-* components. But we don’t want to have this gap on the first and last column, so we adjust this gap with the margin property of the .row element.

This is the default value defined by Bootstrap. If you don’t specify any other values these are the ones that are applied.

no columns

If we triple that value:

no columns

Notice that the left margin for the first column and the right margin for the last column has been increased as well. To adjust this we need to specify a negative value to the margin property for the .row:

no columns

I know it is quite hard to understand the css but I found a very good article explainig it by Erik Flowers, so let me just put the link here.

I will continue writing about Bootstrap 3 in my future articles. Next thing I would like to write about is the customization of buttons. So stay tuned if you are interested.


When someone starts to develop an application it’s hard to know all the great tools that exist outside to help you make your life easier. Vagrant is one of them.

As a start let’s assume you have already chosen a distributed version control system (DVCS) that allows you to upload your code to a common place storing your version history and making easier to share the code through multiple developers. I use Git along with GitHub, so will refer to it from now on. Once you have done that you are ready to face a new challenge.

Anyone with permission can download the code you have uploaded to GitHub, but that does not mean it is going to work in your machine. You will probably need to install dependencies before making it work. You may have created a text file to define those dependencies or just added them in the README file. There is a better way of doing this though: use Vagrant.

Vagrant allows you to build and configure a virtual machine installing all the dependencies that you have previously defined for your project. Using Vagrant you can easily create the same development environment in different machines wrapping it in a virtual machine. You won’t have to install packages manually and the development environment will be synchronized so that everyone has the same configuration.

Vagrant works on top of different virtual machine providers. The built-in option to Vagrant is VirtualBox, which is also free and available on every major platform.

In this post I will describe how to use Vagrant with VirtualBox in Ubuntu 13.10.

Install VirtualBox and Vagrant

First thing is to install VirtualBox and Vagrant. To install VirtualBox type in your console:

Download and install Vagrant.

Initialize Vagrant

Go to your project root and run:

It creates a file called Vagrantfile. It is the configuration file for Vagrant in that specific project. There is a Vagrantfile per project. We will be editing this file along this article. Let’s leave it as it is for now.

Next thing we need to do is to add a box to our Vagrant environment. A box is a base image of a virtual machine that saves us the step of building a virtual machine from scratch.

We are not linking the virtual machine with our project yet, we are downloading a base image to our machine and storing it under /home/yaiza/.vagrant.d/boxes/. This image is global for our Vagrant environment and can be used by any Vagrant project. Vagrant stores it locally in order to make the process quicker once we have everything installed and configured.

A list of availabe images can be found here. We have chosen precise64 that is equivalent to Ubuntu 12.04 LTS 64-bit.

If you had already added the precise64 box to Vagrant for a previous project you can skip that step. You can check which boxes Vagrant has locally installed running:

Now we need to define which box we are using in our project. Edit the Vagrantfile:

Start Vagrant

We are ready to start our virtual machine. Run the command below:

This command imports the virtual machine image to our project creating a folder under project_root_folder/.vagrant/machines/default/virtualbox/. All the changes we make to our precise64 virtual machine will be reflected in our specific project image and not in the global one we defined for Vagrant. It also sets up a ssh connection to our virtual machine.

To get ssh access to your guest machine type in the console:

You are now in the virtual machine you just created.

Vagrant creates the /vagrant/ folder in your guest machine that is shared and synchronized with your project root (the one with the Vagrantfile) in your host machine. Every change that you make on that folder in your guest machine will be reflected in your project in your host machine and the other way around. This way you don’t need to edit your files from your guest machine, you can do that locally in your machine with your favourite editors.

Automated provisioning

Vagrant allows you to define the software you want to be installed automatically when running vagrant up so that your guest machine is ready to work with all dependencies already installed.

This is done creating a file called bootstrap.sh.

You can see below an example of a bootstrap.sh file that installs the latest version of node.js and mongodb. The download directory is /home/vagrant/ and the working directory is /vagrant/. All the commands defined in bootstrap.sh are run as sudo.

Basically you define in that file what you would do manually to install your dependencies. It is important that you define every dependency you use for your project in order to leave the virtual machine correctly configured to be used by any other person that downloads the project.

Configure now Vagrant to run this shell script when setting up our machine. Edit the Vagrantfile as below:

Now, when you run vagrant up Vagrant will create your virtual machine and will provision it automatically as defined in bootstrap.sh.

If you don’t want to provision it when running vagrant up you need to type:

Or if your machine is already up and all you want to do is to run the provision type:

Port forwarding

Quotting official documentation “Port forwarding allows you to specify ports on the guest machine to share via a port on the host machine. This allows you to access a port on your own machine, but actually have all the network traffic forwarded to a specific port on the guest machine.”

This allows us to access to web pages in our guest machine from the browser installed in our host machine.

Edit the Vagrantfile file to specify the port to be forwarded. In the example above, the web server is running under the port 3000 in the guest machine and we are accessing through port 4567 in the host machine:

Reload the virtual machine:

You can access now to your guest web server typing in your browser

Add Vagrant to your repository

You want to upload your Vagrant files to your git repository so they are downloaded with the rest of the project and people can reproduce development environments easily. Add bootstrap.sh and Vagrantfile to your git repository. You can ignore the .vagrant/ folder since it will be created when running vagrant up.

Setting Up An Android App Build Environment With Android SDK and PhoneGap in Ubuntu 13.04

Native Android applications are written in Java, but you don’t need to write applications using their native language any more since the PhoneGap framework is out there. PhoneGap allows developers to build mobile applications using HTML, Javascript and CSS, without caring of native languages. It also provides an API to connect to device features such as Camera, Contacts, Media, …

The advantages and disadvantages of PhoneGap apps versus native apps have been discussed many times in different articles. Briefly, we could say that the main advantage of PhoneGap apps is that they can be built using web technologies knowledge (HTML, Javascript and CSS) without having to learn specific programming languages for each platform. You can write one unique application and get builds for Android, iPhone, Blackberry, … On the other hand, its main disadvantage is the performance. PhoneGap apps are slower than native ones. This is because when you do a Javascript call, it needs to go through the PhoneGap API until it touches the final feature, while in native applications that communication is direct. Thinking on this, for mobile applications focused on data rather than on interacting with the hardware I would go for PhoneGap apps. On the other hand if you need to build an application that makes an intense use of the hardware as games then you may think in writting a native app.

After this small introduction, let’s start to prepare our environment. The official IDE (Integrated Development Environment) for Android is Eclipse but the purpose of this article is to run an Android application using only the command line interface. I try to avoid Eclipse due to its weight which makes my machine run as a turtle.

Install Android SDK

First of all we need to install Android SDK (Software Development Kit). As it is written in its web page, the Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.

Download the SDK Tools. They also offer the ADT Bundle that integrates Android SDK, Eclipse and ADT plugin. For this post we only need to install the SDK Tools only.

Select the package for Linux 32 & 64-bit, download it and extract it in the HOME folder. This will give you the android-sdk-linux folder in your home directory ($HOME).

We must add the $HOME/android-sdk-linux/tools and the $HOME/android-sdk-linux/platforms directories to our PATH variable. We do that editing the .profile file:

Add the following line at the bottom of the file:

To make the change effective (so that we don’t have to log out and back in), run:

We also need to install java and ant:

Now start the Android SDK typing in the console:

In the shell you will see the error message “Error: Missing platform-tools” but the Android SDK Manager will open anyway suggesting you to install some packages. Install the 11 packages that are selected by default. One of them will solve the error that we got.

Android SDK Manager

Android SDK Manager

A new folder is created under $HOME/android-sdk-linux/ called platform-tools that needs to be added to the PATH variable as explained before. Change the PATH to the one show below. Don’t forget to execute the export command to make changes effective.

We also need to install the adb package.

Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It is a client-server program.

If you are on a 64bit system, you also need to install the following two packages:


Install PhoneGap

Download the last release of PhoneGap and extract the .zip file under the $HOME folder. We get the ~/phonegap-2.8.1/ directory.

Add the bin dir to the PATH variable in the ~/.profile file. Run the export command afterwards.

We are now ready to create and build a project using the command line interface.

Create an AVD (Android Virtual Device)

We may want to test our applications in an Android Emulator before installing them in a real device.

An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator.

To create a new AVD we need to generate first a list of system image targets so we get the target ids that we will use later for the creation.

This is what I get:

We can now create an AVD choosing one of the targets listed above.

android create avd -n -t

Where myAndroid is the name I give to the virtual device and android-17 the id of the configuration I chose. Instead of android-17 we can use the id 1.

You can run the emulator typing in the console:

Android Emulator

Android Emulator

To delete AVDs use the command:

In case you find errors when trying to delete an AVD, you can do it using the hard way. Go to ~/.android and delete the .ini file of your virtual device.

Create our first Android app

We could create a pure android project using the android create project command from the SDK. But since we don’t want to program a native application we will create an Android project through PhoneGap so we can use our HTML, Javascript and CSS files:

The command above corresponds to create path_to_new_project package_name project_name. The package_name should be prefixed accordingly with 3 namespace. Example: com.companyname.projectname.

It creates the myAndroidApp directory which contains everything we need to build our final app from it. The subfolder myAndroidApp/assets/www/ is the destiny for our HTML, CSS, JavaScript sources .

If you already have a web project you can copy your files under myAndroidApp/assets/www/ directory, if not you can start to create your project under it just as a pure web application.

Build your project:

By default the build is set to –debug. This option enables users to debug and interactively modify their applications during runtime. When your application is ready to go to production you will want to build in –release mode.

Run your application in the emulator:

If you have more than one AVD you need to specify a target:

Display logs:


Set up an Android device

You can deploy and debug your application into a real Android device just as you would on the emulator.

First of all you need to set up your Android device enabling USB debugging on your device. On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development. On Android 4.0 and newer, it’s in Settings > Developer options. On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.

In the AndroidManifest.xml file, we need android:debuggable=”true”. It comes like that by default, we don’t need to do anything but be sure to disable it before you build for release.

For Ubuntu 13.04 you don’t need to define any rules but you need to do it if you are using older versions. For the latter case follow the next steps:

Log in as root and create this file: /etc/udev/rules.d/51-android.rules. Use the format below to add each vendor to the file:

In this example the idVendor is for LG. You can find a list of vendors here.

Now execute:

And we are ready to install our .apk application to the device:


Using device features via PhoneGap

If you need to use a device feature, for example your phone camera, you need to add to your .html file the cordova.js script that is already under the myAndroidApp/assets/www/ folder:


Adding plugins to your project

You may need to add plugins to your project. You can find the code and files for all supported plugins here.

To install the plugin copy the .js file to your project’s www/ folder. Let’s take the childbrowser plugin as an example. I will just follow the instructions that come in its README.md. The plugin may make use of more files besides of the .js file. You then need to copy all those files that are under the plugin www/ folder into your project’s www/folder. In this example we have to copy the childbrowser.js file and the www/childbrowser/ folder.

Add to your .html file the cordova.js and childbrowser.js scripts that are already under the myAndroidApp/assets/www/ folder.

Create a directory within your project called src/com/phonegap/plugins/childBrowser and move ChildBrowser.java into it.

Add the following line to your myAndroidApp/res/xml/config.xml file:

The plugin is ready to be used within your project.

If you plan to use the PhoneGap Build service, you need to read the instructions of how to include a plugin in the project correctly. You won’t need to do most of the steps defined above since the PhoneGap Build will do them automatically for you.

That’s all for now. Let’s start coding our Android application!

Django tutorial: creating the back-end for the Restaurant Picker app

I was looking for documentation to learn jQuery Mobile and found this great tutorial written by Stéphanie Walter. It covers the front-end of a mobile application using jQuery Mobile.

Every application needs of a front-end and a back-end development. If we simplify the concepts we could say the front-end part is responsible of the user interface and the back-end is responsible of the database access and processing of the data.

I have decided then to write the server-side code for this Restaurant Picker application. After asking for permission to Stéphanie to use her example and front-end code I took the chance to write this Django tutorial. This tutorial doesn’t cover the deployment to production and everything is treated in a development environment.

Django is an open source web framework written in Python which follows the model–view–controller (MVC) architectural pattern. If you know Python I find it quite easy to start to code a web application, most of the most used functions are automated and you can use them out of the box. Besides, it has a big community and clear documentation.

As I said I will use the Restaurant Picker example and the code generated in the tutorial I linked above. You may want to read those specifications since those are the ones we are going to follow. As a summary in the image below you can see the different screens of our application:


Let’s start to code. I will assume you already have django installed, if not you can follow the installation guide.

Setting up the project

The first thing we need to do is to create our project and application folder structure. One project can have multiple applications. The idea behind this is to follow the DRY (Don’t Repeat Yourself) principle so that you can isolate applications in order to be reused by other projects. In our example we will have one project with only one application.

To create our Django project called rest_picker type the following command in the console:

As a result we will get:

We will define the global parametres of the project in the files above later.

To create our aplication, called restaurants inside our rest_picker project we move into the root project folder and once there we must type in the console:

A new directory is created called restaurants with specific files for this application.

Now we need to create a database. There are many options when choosing a database (postgres, mysql, oracle, …), we will go for the easiest one for Django, SQLite3. Django will create it for us automatically once we define it in the settings.py file. If you have choosen one of the other options you will need to create the database first by yourself.

Let’s edit the settings.py file for a SQLite3 database and define the TIME_ZONE:

Remember of changing the path to the one in your machine.


Now we need to define the database schema for our application. We do this defining Django models. Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field.

Let’s remember the screens to think how many tables and which fields our app needs.

  • A screen listing kind of foods
  • A screen listing towns
  • A screen listing restaurants
  • A screen with the details of the restaurant: name, description, what to eat, web site, phone number, address, postal code, a url for google maps, number of stars, food and town

We need then a table for kind of foods, a table for towns and a table for restaurants. The fields food and city of the restaurant table will be linked in a many2one relation to the Food and Town tables.

We want to display an image with the food, and also an image for the restaurant and an image of a map with the restaurant location. We need to store those images in the server and store the path in the database so we can retrieve them when needed.

This is how the models.py file must look like:

We overwrite the __unicode__() method to return a human-readable representation of the model instead of str(obj) that is what is defined by default.

The menu field will store a list of food and drinks that are offered in the restaurant. This list should be entered separating elements with semicolons so that we can process it later to display it in the correct way.

The ImageField needs of a more detailed explanation. The upload_to parameter defines a relative path to the MEDIA_ROOT parameter defined in the settings.py file. We will upload the images to a media/image/ folder inside the root project. We need to create those folders, getting the folder structure detailed below:

We edit now the settings.py file:

Remember of changing the path to the one in your machine.

MEDIA_ROOT defines the absolute path where the image will be stored. Since we have defined the upload_to attribute of ImageField as images/, the images will be stored under /home/yaiza/dev/rest_picker/media/images/. MEDIA_URL defines which url serves the media file, we will understand this parameter better when we see the urls and views files.

Before running the command to create the tables we need to add our application to the list of INSTALLED_APPS in the settings.py file. We will uncomment the django.contrib.admin line as well that is responsible of generating the automatic admin interface that we will see later. We can leave the ones that are activated by default as they are since they define basic operations as authentication, a session framework, a framework for managing multiple sites, …

We are ready to run the command to generate the tables in our database:

This command looks for new applications in the list of INSTALLED_APPS in the settings.py file and creates the tables in the database. Since it is the first time that we run it and we chose SQLite3 as our database it will ask for the creation of a superuser. Go ahead and create that superuser.

[Note: The syncdb command only creates new tables but it doesn’t notice changes in an existing model, hence, it doesn’t modify existing tables. To do this easily you may want to have a look at South, a tool for database migrations for Django applications.]

We have already created the database schema for the application.

Admin Interface

By default Django provides an admin interface that is reading the models that we have just created. We just need to define which url is going to serve our admin interface. We do that through the rest_picker/urls.py file:

This file defines the URLconf module that maps urls with given Python code (views) or HTML templates. The path to get to this file was defined by default in our settings.py file when we created the project (ROOT_URLCONF = ‘rest_picker.urls’). You can change this if you want to.

The first argument of the patterns function is a string prefix (we are not using this prefix for now, we will explain it later), the following ones are url functions. The url function accepts two arguments minimum: a regular expression and either the view that must be called or a redirection to other URLconf module, when that url is met. In this case, we are referring to another URLconf module using the include function. This module comes by default with Django.

If we look at the regular expression r’^admin/’ this means that adding admin/ to our base url we will get the admin interface. Let’s check it.

Django comes with a lightweight development web server on the local machine. By default, the server runs on port 8000 on the IP address (localhost). You can pass in an IP address and port number explicitly. (Django recommends not to use this server in production since it has not gone through security audits or performance tests).

To start the dev server type in your console:

Our default base url is: http://localhost:8000/.
To get our admin interface: htp://localhost:8000/admin/

The login and password are the ones you entered for the database superuser.

We can’t see a menu to enter data for our application yet. We need to do something else first. We have to create restaurants/admin.py to add the models and fields we want to be able to edit through the admin site:

We have used the default interface for Food and Town and we have customized the Restaurant one. We could have used admin.site.register(Restaurant) but we have defined sections for the Restaurant model and we have ordered the fields.

This is the result of the Admin Site:

Admin Site

Admin Site

You can add all the data you need for a restaurant through the admin site now.

URLS and Views

Let’s design the public sites now. We need to define an url for each screen and a .html template linked to it along with a view if any data processing is needed.

We will define a specific URLconf module for the application under the restaurants folder that will be referred from the global URLconf module of the project. This application URLconf module maps urls with views (Python code) or templates (HTML). In case of a view it will call the corresponding HTML template.

Template Diagram

Template Diagram

By default Django looks by default for a subfolder called templates under the application root folder. In order to avoid conflicts between templates of different applications sharing the same project that may have the same name, is a good practise to add a subfolder under templates named as the application. As a result we will place our templates under restaurants/templates/restaurants/.

I have chosen rest_picker as the url for our application, getting a base url as http://localhost:8000/rest_picker/.

Let’s think in the workflow to define urls and parameters that we need to pass from one screen to another through the url.

  1. Choose a food: index.html
  2. URL: http://localhost:8000/rest_picker/
    We need to pass the food id to the next screen in order to do a filter to only show cities that have restaurants with that food.

  3. Choose a town: choose_town.html
  4. URL: http://localhost:8000/rest_picker/food/<food_id>
    For the next screen we need to pass the food id and the town id to display only restaurants for that town and with that food.

  5. Choose a restaurant: choose_restaurant.html
  6. URL: http://localhost:8000/rest_picker/food/<food_id>/town/<town_id>
    We only need to pass the restaurant id to the next screen.

  7. Restaurant details: rest_detail.html
  8. URL: http://localhost:8000/rest_picker/rest/<rest_id>
    Final screen.


We are saying that all the urls that are like http://localhost:8000/rest_picker/ must look into the restaurants/urls.py file. The namespace parameter, again, is to avoid naming conflicts for different applications in the same project.


There are generic views to allow you write common views of data without having to write too much code. ListView is one of them. When the regular expression is met (http://localhost:8000/rest_picker/) it calls the template defined in template_name (index.html). It looks for it at the folder templates, since we created the restaurants subfolder under it we need to specify the relative path. It passes a list with all the objects of the Food model (food_list = _list) to the template. You can use a different name for this list of objects using the context_object_name attribute. Also, if you want to define a subset of objects you can use the queryset attribute along with a filter, for example something like queryset = Food.objects.filter(name_startswith=’H’).

The name attribute we have defined for all urls lets you refer to it unambiguously from elsewhere in Django so you don’t have two urls with the same name. Again it is to avoid a naming conflict.

The rest of urls call to a function defined in views.py since they need of some Python code before calling the HTML template. You can see that the first parameter in the patterns function is not empty this time, it is set as restaurants.views. Because of this when you define the function to be called when the regular expression is met you only use choose_town. If the prefix would have been empty you would have had to use restaurants.views.choose_town.

Let’s look at (?P<food_id>\d+). Using parentheses around a pattern captures the text matched by that pattern and sends it as an argument to the view function; ?P<food_id> defines the name that will be used to identify the matched pattern; and \d+ is a regular expression to match a sequence of digits (i.e., a number). So, if we have http://localhost:8000/rest_picker/food/3 we will be calling to the function choose_town inside views.py and passing to it food_id=3.

The last part is used to serve the images uploaded through the admin site. This way of serving static files is ONLY valid when working with the development server where we can use the django.views.static.serve view. For production you will need to set up your web server to serve static files. This is out of the scope of this tutorial, you can find more information about this in the django site.


The render function calls the HTML template and it passes the parameters needed in a dictionary to that template. Those parameters are processed in the Python code.

choose_town builds a list with the towns that have restaurants with that food_id and also the number of restaurants in that town with that food. This number is the one displayed in the bubble. We also transfer the food_id because we will need it later in the workflow.

choose_restaurant gets the restaurants with that food_id and town_id.

restaurant processes the field menu of the Restaurant model. We said before that we had to separate the elements in the list with semicolons when entering through the admin site. We are getting now this elements and passing them to the html template. The message parameter is empty by default.

vote is the function that processes the votation. It calls again to the restaurant html template but passing a Thank you message for voting. As this is a Model-View-Controller framework, the calculation of the votes should be contained in the models.py file and not in the views.py file to keep the independence of the parts. We have done it this way for simplication.

HTML templates

Now we will use the templates generated in the jQuery Mobile tutorial. We have to copy the .html files (index.html, choose_town.html, choose_restaurant.html, restaurant.html) under restaurants/templates/restaurants/.

The .css files are static files. Django looks for these files in a static folder placed under the root app folder. We need to create that directory (restaurants/static/restaurants/). In order to reuse the paths we used in the .html files of the jQuery Mobile tutorial we will create an images and a js folder under it and we will copy here all the resources. Let’s have a look how does the folder structure looks like now:

Let’s look at the templates now. We need to change some things to retrieve the data from our database.


I have highlightened the lines that have been changed adding Django syntax.

The first thing we have to do is to change the way of defining static files (.css, .js, .png). We specify that the element is static so that Django knows where to look for those resources, and then the relative path and the name to the resource.

We use the list of Food objects that we passed in the ListView (food_list) to go through all the foods. We display the name and the image associated to that food and also the url that must be called when clicking in one element passing the food_id.

The only thing that is going to change from one template to another is the body, so I will just copy the body for the rest of templates.


We do the same here but going through the list of towns. This time we pass two parameters to the url linked to the town, the food_id and the town_id. And besides the name of the town we display the number of restaurants in that town for that food.


For the list of restaurants we display the image of the restaurant, the name and the starts. And we pass the restaurant_id to the template that will be called when clicking in a restaurant.


For the restaurant.html template we must replace all the fix elements for dynamic oness. We use {{restaurant.name}}, {{restaurant.desc}}, {{restaurant.web}}, … I have also added the display of a message in the line 9. This message is the Thank you message that will only be displayed after a votation. The votation is submitted when we change the selection of the drop-down(onchange=”this.form.submit()”), for this reason we have to add the option “Choose your vote“. When submitted, it calls the vote view that we saw before that will do the calculations of the votes, storing the new value in the database and displaying the restaurant page with the Thank you message.

Because we have added another option to the drop-down list we need to adjust the .css file.


We have completed the back-end of our application. You can find the code in github. Remember that you need to change the paths in the settings.py file to your own paths. You can ignore the requirements.txt file that is part of Python virtualenv and the migrations folder that is part of South since they have not been covered in this tutorial. Also it is very important that you include tests for your application. This is as important as the application code and it makes a difference in your application.

I hope you have found this tutorial useful!

The NERD Tree plugin

I use vim as my editor and I want to share a great plugin I found for it: The NERD Tree.

As vim.org defines it,

The NERD tree allows you to explore your filesystem and to open files and directories. It presents the filesystem to you in the form of a tree which you manipulate with the keyboard and/or mouse. It also allows you to perform simple filesystem operations

To a better understanding of what this plugin does you may want to watch the video below created by Nettuts+.

In the video you can find a great explanation of the plugin and its usage but the instructions of how to install it are not up to date. To resolve this I have written updated instructions to install the plugin. First of all you will need a github account. Once you have a git account you are ready to follow the steps defined below.

  1. Install pathogen plugin

  2. If you don’t have pathogen installed you will need it so that you can easily install the NERD tree plugin from git. Pathogen makes it easier to install plugins and runtime files in their own private directories.

    Download the plugin from github and move it to .vim folder:

    If there is no bundle and autoload folders there you need to create them:

    Edit your vimrc (~/.vimrc) adding:

  3. Install The Nerd Tree plugin

  4. Generate documentation

  5. You can generate documentation using the pathogen plugin.

    In the shell type:

    Once you are in the editor:

    You are ready to start to explore all the commands you can use. Enjoy it!

Hello world!

Welcome to my blog!

I’m a programmer who wants to improve her skills and learn new technologies. I’m starting with web and mobile technologies but that’s not the only thing I want to learn, my plan is to combine this learning with other things and courses I discover in the way.

For this new stage the first thing that I have done is to publish this site, nothing complicated, just a platform where I can log the things I discover and that may be useful for someone else. A minimalist and clean blog, that’s all I need for now.

What else do I need? A twitter account (@yaizabailen), professionally you don’t exist if you don’t have a twitter account so I have created a professional one for me. I don’t have anything there yet so I’m not even advertising in the site. And also I will need a git account, I already had one although I didn’t use it because I used bazaar. It obvious that git has won the battle against bazaar though, so it is important to have a git account.

And now, let’s start reading and finding out what is out there!