coding sampler

12
Upgrade your brain the Linux Format way # 1 for Free Software Web Android Concepts Python Learn Master both Django and Ruby on Rails Build your own maps and photo apps Learn tricks useful in any language An hour to learn, a lifetime to master Take your coding skills to a new level 2013 Coding Academy CBN31 2012 £12.99 CBN47 2013 PRINTED IN THE UK £12.99

Upload: future-plc

Post on 22-Mar-2016

220 views

Category:

Documents


0 download

DESCRIPTION

http://www.myfavouritemagazines.co.uk/computer/coding-academy-2013/

TRANSCRIPT

Page 1: Coding sampler

Upgrade your brain the Linux Format way

#1 for Free Software

Web AndroidConcepts PythonLearnMaster both Django and Ruby on Rails

Build your own maps and photo apps

Learn tricks useful in any language

An hour to learn, a lifetime to master

Take your coding skills to a new level

2013

CodingAcademy

CBN31 2012 £12.99

CBN47 2013 PRINTED IN THE UK £12.99

Coding A

cademy 20

13

Page 2: Coding sampler

4     Coding Academy 2013

Contents

Code Concepts

Ruby on Rails

Types of data ................................................................................................................8Write a short program ....................................................................................10Abstraction ..................................................................................................................12Files and modules ................................................................................................14Using an IDE ................................................................................................................16Clone a Unix command I .............................................................................18Clone a Unix command II ...........................................................................20Clone a Unix command III .........................................................................22Modules ..........................................................................................................................24Storage ............................................................................................................................26Data organisation ................................................................................................28Data encryption .....................................................................................................30

Ruby: Write your first program ...........................................................36Ruby: Modules and blocks ......................................................................40Ruby: Mixins, block and yields .............................................................45Ruby on Rails: Learn the syntax .........................................................50Ruby on Rails: Test-driven development .................................54Ruby on Rails: Site optimisation .........................................................58

ALERT!We’ve put all the code for all the tutorials online. Just download and unzip the following archive: www.linuxformat.com/files/ca2013.zip

CBN47.contents.indd 4 6/26/13 4:15 PM

Page 3: Coding sampler

Coding Academy 2013    5

Contents

Code Safari

Code Android

Code Python

Starfield: Learn new languages ..........................................................64Scheme: Learn the basics ........................................................................68Scheme: Recursion ............................................................................................72Scheme: High order procedures .......................................................76Getting started with Haskell ...................................................................80Dabble with Lisp ....................................................................................................86Kotlin: Moving on from Java....................................................................90

Local databases ....................................................................................................96Remote databases..........................................................................................100Map your photos ...............................................................................................104Talking to devices ..............................................................................................110Taking pictures .....................................................................................................114Shape up with OpenGL .............................................................................120OpenGL: textures and touchscreens .......................................126

Django: Build your first web app .....................................................134Django: Data and forms ............................................................................138Django: Using Bootstrap ..........................................................................142Django: Pro tips ...................................................................................................146Python: Get started with Clutter ....................................................150Python: Clutter animations ..................................................................154Python: Streaming video .........................................................................158

CBN47.contents.indd 5 6/26/13 4:15 PM

Page 4: Coding sampler

32 Coding Academy 2013

Subscribe today

What You’ll Pay: UK – pay £14.99 by quarterly Direct Debit, or £59.99 for a year’s subscription (13 issues)

Europe – pay £99.99 a year

Rest of the world – pay £107.99 a year – equivalent to £8.31 an issue

Get all this: Exclusive access to the LXF subs-only area, featuring magazine PDFs, complete issues and coverdisc downloads.

A digital edition of every issue from our subs-only area on your PC, iPhone or iPad.

Save money on the shop price.

Get each issue delivered to your door – a week before it hits the shops (UK only).

Discount on Linux Format merchandise.

Asubscription makes the perfect gift for a loved one!

Subscribe today and get Linux Format for just £4.61 an issue

T ake advantage of our fantastic subscription offer and subscribe to Linux Format for just £14.99 every three

months or £59.99 for the year. With this offeryou could save as much as 29% per year.

Our subscribers are our most loyal readers, and as a thank you we like to make sure you not only get a great price, but also tons of other benefits.

CBN47.subs.indd 32 6/26/13 11:27 AM

Page 5: Coding sampler

Coding Academy 2013 33

Save 29% per yearGet thousands of DRM-free tutorials, features and reviews

In the USA or Canada? Subscribe for just $139 a year, or $35 every three months

Go to www.imsnews.com/lxf-A049or call TOLL-FREE on 1-800-428-3003 and quote ‘A049’

All savings are based on current newsstand prices. Payment is in GBP unless otherwise stated. You will receive 13 issues of Linux Format a year. If you are dissatisfi ed in any way you can write to us or call us to cancel your subscription at any time and we will refund you for all unmailed issues. International subscribers please allow up to eight weeks to receive your fi rst issue. Access to the subscriptions-only archive area is

strictly for personal use and not available to digital subscribers. Offer ends 10 October, 2013.

Visit www.myfavouritemagazines.co.uk/LINP31or call our hotline on 0844 848 2852 and quote LINP31

For international subscription offers go to: www.myfavouritemagazines.co.uk/LINP31

Fig. 1 The benefits of subscribingHello Linux Format reader!

Don’t bother subscribing; it’s not worth it. Instead, write to us and let us know what you want to see more of and what you want to see less of.

We want your cash!

Buy it on the newsstand in the UK and

save our costly export fees.

Congratulations on transcending materialism. Perhaps you’d like more than 2,700 DRM-free

PDFs covering everything from Asterisk to Zshell, available exclusively to LXF subscribers.*

Well done! You’ve saved yourself the hassle of

getting down to the shops – town centre parking is

a nightmare these days.

Read, enjoy, come back next issue.

Is this the fi rst time

you’ve read LXF?

Do you buy LXF more than

a couple of times a year?

Are you a subscriber?

Are fi nancial incentives important

to you?

Do youlive in Foreign

and visit the UK more often than

once amonth?

You should subscribe. At just £59.99 a year for

UK readers, it’s far cheaper than buying each issue individually.

You should subscribe. You’ll get your copy up to a week before it hits the shops, and be able to download

a digital version.

Do you own

a TARDIS?

You are the Doctor, and I claim my prize. Also, please take me back to

1968 so I can see the Elvis comeback special!

YES

YES

NO

NO

YES

NO

NO NO

NO

NO YES

YES YES

*That’s all of our back issues, starting with issue 67 andgoing right up to the magazine you’re holding in your hands.

CBN47.subs.indd 33 6/26/13 11:27 AM

Page 6: Coding sampler

Dr. Racket is our tool of choice for programming in Scheme. It provides many useful features, including bracket balancing and tools for debugging code.

68     Coding Academy 2013

Scheme Coding

But it’s a great programming environment, and you can make it work with standard Scheme by going to the Language > Choose Language menu and selecting R5RS from the window that appears. With Dr. Racket happily installed, we can start programming.

Simple expressionsAll programming is really about manipulating information, data. That data can represent anything, from the ingredients used to mass produce a certain kind of biscuit to the position of a robot’s arms and claws on a factory assembly line.

In order to manipulate this data, we must find ways to represent it that a computer can understand, and we must be

Scheme: Learn the basics In part one of a new series, Jonathan Roberts explains how to get started with this simple but popular programming language.

In the pages of LXF, we’ve demonstrated many different programming languages, including Assembly, Python, PHP, Java and more. We have never, however, covered a

language called Scheme, which is a shame really, as many of the most well regarded introductions to programming and computer science choose it as their teaching tool.

While there are many reasons for this, suffice it to say that Scheme is a popular choice because it’s a simple language with little syntax to learn. This means it does a wonderful job of demonstrating many important principles that are obscured in other languages by their more complex syntax.

As well as being a good language for new programmers, Scheme’s also interesting to those with more experience. Unlike most of the languages we focus on in LXF, it’s primarily a functional language, as opposed to an object-orientated or imperative one. As such, it’s a great chance to see some different approaches to common problems.

With all that in mind, over the next three issues we’re going to introduce you to Scheme. To begin with, we’re going to focus on some of the basics of Scheme, with later articles looking at some particularly functional approaches to solving problems.

Installing SchemeAlmost all Linux distributions come with a Scheme interpreter built in. It’s called Guile, but it’s pretty complex and we won’t be using it. Instead, we’re going to use a tool called Dr. Racket, which you can find in some distributions’ repositories or by heading to its official website: http://racket-lang.org/download.

Dr. Racket is actually designed to work with a particular dialect of Scheme (which is itself a dialect of Lisp, the language Emacs is written and extended in) called Racket.

Dr. Racket is a programming environment that makes coding in Scheme much easier than in a plain text editor. Its main window is split in two.

The top half can be used for entering, saving and loading entire programs, made up of many functions and definitions. When you’ve completed work on part of a program and you want to see how it works, press the Run button in the top-right of the screen and Dr. Racket will evaluate the program and display any results in the bottom half of the window.

As well as being used to display results of

programs entered in the top half, the bottom half of Dr. Racket’s main window can be used as an interactive interpreter. If you type Scheme expressions in to it and press return, it will immediately show the results.

This is a handy way to quickly check that small snippets of code work as you expect. It’s also the part that we’ve used throughout this month’s tutorial.

There are other parts of Dr. Racket that make it an appealing environment to code in. Elsewhere in the article, we’ve mentioned its

automatic bracket balancing, which helps us to avoid syntactic mistakes. However, it also provides a number of other tools to help us spot mistakes in our code.

For instance, if you try to run a program with a mistake, Dr. Racket will provide a description of the error and even highlight the part of the code where it occurred. What’s more, when we start working with more complicated programs the Debug button in the top-right can help us track what the program does and understand how it evaluates different types of expressions.

Dr. Racket

CBN47.scheme_165.indd 68 6/25/13 6:05 PM

Page 7: Coding sampler

Pretty-printing and bracket-balancers make dealing with Scheme’s many brackets much easier. Once you get the hang of the brackets, you’ll come to love the lack of ambiguity.

Coding Academy 2013    69

Scheme Coding

Scheme: Learn the basics

able to define the processes that we will use to manipulate it, too. Doing this for complex kinds of data is obviously very challenging, so we’re going to start off with a far simpler type: numbers.

In Scheme, numbers and many common (and some not so common) operations that you might perform on them are known as primitives – they’re built in to the language itself. You can experiment with this in the bottom half of the Dr. Racket window.

This part of the window is an interactive interpreter: you can type Scheme expressions in to it and the result of evaluating the expression will immediately be displayed to you. Try typing a 5 and pressing return and you’ll see another 5 – this tells us that the result of evaluating a simple number (a primitive) is the number itself.

Doing calculationsIf you combine numbers with their basic operations, you can use Dr. Racket’s interpreter and Scheme as a simple calculator, although the syntax is a bit different from what you might be used to from school: > (+ 5 5)10> (- 8 4)4> (* 2 3 4)24

As you can see, the operation comes first and the numbers it’s applied to (the operands) come afterwards; what’s more, the whole expression must be wrapped in brackets. This syntax has two advantages: first, you can easily apply the operation to as many numbers as you like without having to repeat the symbol.

The other advantage is that there’s never any question about what order to perform the calculation in, just remember that you evaluate the inner-most expression first and work your way out: > (+ 3 (* 2 4) (+ 4 (- 8 3)))20

In this example, you calculate (- 8 3) first, then (+ 4 5) and (* 2 4), before finally doing (+ 3 8 9). To make it easier to keep track of all the brackets, Dr. Racket will highlight matching brackets and which part of the expression they apply to as you close them off.

Our lives are also made easier thanks to a convention called pretty-printing. Rather than writing the entire

expression and all its sub-expressions on a single line, you can break it, aligning all the operands (the numbers each operation is applied to) vertically: > (+ 3 (* 2 4) (+ 4 (- 8 3)))

VariablesWhen we’re programming, the data we’re working with rarely represents just numbers. For instance, a number might be the quantity of elderberries needed to make 30 litres of elderberry wine, or it might be the volume of a bottle needed to store the wine that’s being made.

To make our program more manageable as it becomes more complex, to make it more readable, one of the most important things a language can do is let us give the numbers we’re working with names.

In Scheme, this is done with the define statement: > (define pi 3.14)> (define radius 3)

As you can see, it works just like any of the mathematical operators in our earlier example. The only difference is that

At the start of this article, we said one of the things that sets Scheme apart is it’s a largely functional language, as opposed to an object-orientated or imperative one. If you’re new to programming, this might not have meant much to you, but we’ve got you covered.

These three obscure sounding titles refer to different programming paradigms – that is, particular ways of thinking about problems and programming solutions for them, different styles of programming.

When programming in an imperative style, the main focus is on recording and adjusting the state of the program. This is often done through the use of variables and functions that modify their value directly. This particular paradigm

matches the way programs are executed on the hardware, but it can make programs harder to develop and test, since the programmer must take in to account the state of many external variables, not just the inner workings of a single function. That is to say, in imperative languages functions have side-effects. The imperative paradigm is most often associated with Assembly language or C.

Object-orientated programming attempts to resolve the problem of external variables by structuring a program around the idea of separate objects. Each object records its own state, which it keeps separate from the rest of the program. Each object also specifies a number of methods (functions) that let other

parts of the program inspect and modify its state. It models the real world well, where most things appear to us as individual objects. A cooker, for instance, is an object. It has controls, like methods, that let me modify and inspect its state without affecting other parts of the kitchen.

Finally, functional programming attempts to do away with the idea of state completely. There are no external variables, no side effects. This makes designing and testing programs much simpler, since every time a function is run with the same input values, it will return the same output. There’s no need to take into consideration any external variables, or its interaction with any external objects.

Programming paradigms

CBN47.scheme_165.indd 69 6/25/13 6:05 PM

Page 8: Coding sampler

90     Coding Academy 2013

Lesser-known Languages

Juliet Kemp introduces Kotlin, a new project aiming to create a simple, Java-compatible language that fixes some of Java’s flaws.

Kotlin: Moving On From Java

Installing the Kotlin plugin via IntelliJIDEA.

If you’ve closed the bottom window, it will pop up once the Make task in the bottom bar has finished.

Creating a new Kotlin library for your first project.

The aim of Project Kotlin is to create a Java-compatible language that is safer and more concise than Java, but simpler than Scala, the nearest similar

competitor. So Kotlin is a statically typed, JVM-targeted, object-oriented language. It’s not functional per se, but it does

borrow some useful notions from functional languages. It’s an open-source project, and is very much in the development stages, so while it’s mature enough to play around with, do be aware that it’s still something of a moving target. On the other hand, that leaves plenty of scope to get involved!

Getting startedIt’s possible to download a standalone compiler, but it’s much easier to run Kotlin via IntelliJIDEA. Install or fire up IDEA (note that if you’re installing from scratch on Linux, you’ll need to install Oracle Java; it won’t work correctly with OpenJava), then go to Settings > Plugins > Browse Repositories, and double-click the Kotlin plugin to install it.

To start our initial project, go to File > New Project, and create a Java Module project, HelloKotlin. You may need to specify the Project SDK (by clicking New and locating the Java SDK) if you haven’t used IDEA before. On the second page, click the Kotlin box, and create a new library.

You’ll create your first Kotlin source file in the src directory. To view this, click on the HelloKotlin in the top-left corner of the screen, and choose src from the drop-down. You can then right-click on src in the Project window on the top left, and choose New > Kotlin file:fun main(args: Array<String>): Unit {

println(“Hello World”);}

To run it, use the Run menu, and choose DefaultPackage, and you’ll see your file compile and run in the bottom window. Your first Kotlin code! After it’s run for the first time you can use the Run button in the button bar.

CBN47.lesser_known174.indd 90 6/26/13 10:42 AM

Page 9: Coding sampler

Coding Academy 2013    91

Lesser-known Languages

Kotlin basics

Kotlin distinguishes between references which can and cannot be null. By default, a standard Kotlin reference cannot be null; you need to specify if it can be. For example, a regular Int variable cannot be null, and if you try to set it to null, the compiler will report an error.

An Int? can be null, but then if you try to use regular methods with it, the compiler will error on that as well. Here are some examples:fun main(args: Array<String>): Unit { val a = 1; val b : Long = 2; val c : Long? = null; val z : Int? = 3;

val d : Long = a.toLong() + b; //val y : b + c; // this won’t work val e = c?.plus(b); val f = if (c != null) (c + b) else b; val g = //val h = c?.plus(z?.toLong()); // this doesn’t

work! println(“1 + 2 is “ + d); println(“null + 2 with the safe operator is “ +

e); println(“null + 2 with if/else is “ + f);}

If you try to just add b and c, you’ll get a compiler error; you can’t add a nullable and a non-null reference. Instead, you have a couple of ways of dealing with this situation:

Safe calls This is written ?. and the method after the call will be executed only if the reference is not null. Otherwise, the whole thing will return null result, which will be shown by the e option.

If, and the Elvis operator f shows the if/else option: if the nullable reference is non-null, you do whatever you were planning to (here, add b and c); otherwise, you do something else. You can rewrite this as follows:val e = c?.plus(b) ?: b;

using the safe operator for the if clause and the Elvis operator ?: for the else clause. You’ll see that these return different values! Effectively the safe operator is the Elvis operator with null as the else value.

This does introduce a certain element of unpredictability as the price of removing NullPointerExceptions, but then again, NPEs are a bit unpredictable too; at least here we are able to decide what will happen explicitly in the code. You can’t use a nullable in the second half of any of these method calls at all, so adding two

nullables simply won’t work:val c : Long? = null; val d : Long? = 1; val e = c?.plus(d);

Another way of handling results that might be null is to explicitly check that they’re not null using if (a != null); the compiler will notice that you’ve done that and let you go ahead.

There are other implications of following this approach, so make sure that you check out the Kotlin introductory documentation for more information before getting stuck in.

Nullable references

The IDE shows you any problems with your code with those red underscores.

Like Java, Kotlin is an object-oriented language; and everything in Kotlin is an object. This means that you can call properties and functions on any variable. Let’s dive in and have a quick look at some of the basic built-in types that are available in Kotlin.

Numbers are handled similarly to Java, with double, float, long, int, short, and byte types. You can’t implicitly cast between types, but must use toLong(), toShort() and so on. As the code below shows, the standard operator overloading of +, *, -, and so on are all present:fun main(args: Array<String>): Unit { println(“Hello World”); val a : Int = 1; val b : Long = 2; val c : Long? = null; val z : Int? = 3; val y = 4; println(“Class of y is “ + y.javaClass);

val d : Long = a.toLong() + b; println(“1 + 2 is “ + d);}

The keyword val is a read-only way of creating a property (var is read-write; see the next section (Classes and a Program, p92) for more details on properties). Kotlin has strong type inferencing, so when creating a property, you can either specify its type, or leave it blank and let the compiler infer its type for you. If the type you use is ambiguous, the compiler/IDE will let you know so you can clarify the type. You can check the class of a variable with x.javaClass, if it is a class that exists in Java. So far so good; but what about these odd-looking Long? and Int? variables?

Kotlin’s type system is intended to entirely avoid the bane of the Java coder’s life: the dreaded NullPointerException. It does this by distinguishing between references that can be null (nullable references) and references which cannot (non-null references). See the Nullable References boxout below for more on nulls.

Characters (Char) are also basic types, and cannot be implicitly converted to numbers. They go in single quotes. Booleans are a basic type (with true and false values).

Arrays have a get and set function that you can access via [] notation:val myarray = array<Int>(1,2,3,4); val yourarray = array(5,6,7,8); val constructedArray = Array<Int>(4, {i -> i * 2}); println(yourarray[1]); println(myarray[2]); for (x in constructedArray) print(x);

Note that the two constructors here: Array<Type> is used when constructing the array by providing its size and an initialising function to the constructor. array is a library function that just explicitly specifies all the array members. Arrays are zero-indexed, and there’s no need to explicitly specify an iterator when looping over an array.

Strings are either escaped strings, shown by ”string”, which can contain escaped characters, or raw strings, shown by ”””string””” which has no escaping, can contain newlines, and just prints out what’s on the screen.

Finally, function calls are written fun, as with the main function in HelloKotlin.kt. You can also have functions within a class, in which case they are member functions and are called with Java-type dot notation (thing.foo()).

CBN47.lesser_known174.indd 91 6/26/13 10:42 AM

Page 10: Coding sampler

134     Coding Academy 2013

Web Application Frameworks

you configure to your tastes, and some are more involved web application platforms that you can you use to hand-roll your site. By far the most flexibility lies with the latter, and one of the best options out there is Django.

Django is a web application framework that provides an incredibly powerful set of tools for creating web applications quickly and easily. One of the major reasons for Django’s popularity is that it is based on and uses Python extensively. For those of you who have not yet been enlightened to the power and glory that is Python, it is a high-level programming language that makes programming simple, flexible and powerful. Python itself is a wonderfully pleasant and fun tool to use, but combined with Django you have a tool with which you can quickly create web applications, and harness the wealth of functionality built in to Python. In this tutorial, I am going to take you for a quick spin through how to create your first Django application. This tutorial will presume some Python knowledge, but only the basics. By the end of this guide you should have a solid base on which you can continue to grow and extend your Django skills.

Getting startedI am not going to go through the details of how to install Django; you should find it packaged for your distribution and ready to go (as an example, in Ubuntu you can install the python-django package). If you don’t have a package available, and don’t want to go through the hassle of setting up its rather gnarly set of dependencies, you should download the excellent Bitnami stack, which includes a full Django setup ready to go. You can download it at http://bitnami.org/stack/djangostack

The first thing we need to do is open a terminal. We will run a series of commands for doing things such as generating projects and applications, updating our database and running a temporary web server. Let’s begin, though, by creating a new project. To do this, run the following command:django-admin.py startproject pawnstore

Now, I am going to be honest with you. I absolutely love the show Pawn Stars (a show about the trials and tribulations of a pawn store in Las Vegas). We are going to create a web application for managing a pawn store. The above command uses the django-admin command to create a new project called ‘pawnstore’.

In Django, you have a single project, and within it you can have lots of applications. As an example, you might have an application to track the inventory of the store, one for managing sales, and one for co-ordinating who works which shifts. All of these applications can exist in the same project.

Before we create our first application, we first need to configure our project a little. Inside the newly-generated ‘pawnstore’ project you can see a sub-directory called pawnstore. In there is a file called settings.py that describes

Django: Build your first appJono Bacon explains how to get started and takes us for a spin with the Ferrari of web application frameworks… Django.

The web, in it’s many different forms, has been around for a long time. Back in the early days, content was largely static and textual, and over the years we have

seen the web become more dynamic and interactive, and infused with video, audio, animation and more – all from the comfort of our trusty browsers.

Outside of our familiar social networks, video/audio upload sites and other vessels of distraction, some of you may want to build your own fully-fledged website from scratch and put it online. You may want your site to be a homepage, a library management system, a music database, a company records system or any one of a million other types of site. The technology certainly exists to create almost any website you like, but how do you get started?

Fortunately, there are many web application frameworks that make it easy to get a site up and running. Some are pre-built content management systems, such as WordPress, that

Fig 1: The Django admin interface is handy for adding, viewing, and deleting data.

CBN47.django165.indd 134 6/26/13 10:52 AM

Page 11: Coding sampler

Coding Academy 2013    135

Web Application Frameworks

the settings for the entire project. Open this file, and let’s first choose which database we want to use.

Django supports many different databases (including SQLite, MySQL, PostgreSQL and Oracle). To keep things simple, we are going to use SQLite; this is a simple flat-file database that lives inside a file on your computer. To select this, Find the ‘ENGINE’ line and add sqlite3 inside it. It should look like this:‘ENGINE’: ‘django.db.backends.sqlite3’,

You will also need to set the name of your database. Add the following:‘NAME’: ‘pawnstore.db’,

With our configuration all set, now we can create the first application in our project. We are going to create a Django application for managing the inventory of our pawn store, so let’s create an application called ‘inventory’. To do this, we are going to use the manage.py script (inside our top-level pawnstore directory) for the first time. This program is our swiss army knife for managing our project. You will see us use it more and more throughout this article.

To create an application, run the following:python manage.py startapp inventory

This will create a new directory called inventory. Let’s now get started building our application.

Creating our databaseLike other databases, Django stores data in tables, and fields inside those tables. We will need to create our tables and fields, then add data later that we can query and display in different ways. Fortunately, unlike other systems in which we would need to create swathes of SQL to set up our tables, fields, and data, we can instead use the power and simplicity of Python to do this.

Inside our inventory directory is a file called models.py. In this file, we can add Python classes that describe the data structure of our inventory application. To keep things simple, we are going to have two tables: Categories and Items. Each Item will be part of a particular Category.

To add these tables, add the following to models.py:class Category(models.Model): name = models.CharField(max_length=200)class Item(models.Model): category = models.ForeignKey(Category) dateadded = models.DateTimeField(‘date added’) name = models.CharField(max_length=200) description = models.TextField() quantity = models.IntegerField()

Here, each class refers to a different table in our application, and each variable inside the class uses a Django function to describe what kind of data the field is. As an example, dateadded in the Item class is a DateTimeField, and this will cause Django to store the data in a date format, and in some cases display a date picker when the user needs

to enter a date. Another example is the ‘name’ field, which is a CharField; this is a string of text, and this data is typically gathered with a single-line text box, as opposed to a TextField, which usually uses a multi-line text input box.

With the schema of our database all set, let’s now take this schema and generate our database. Do this by running:python manage.py syncdb

You will now be asked a series of questions. When asked if you want to create a superuser, say ‘yes’ and set the username, email, and password to whatever you like. You should then be returned to the prompt. Your database is now created successfully. Let’s now run our project and see what it looks like. To make it simple to view your project, Django includes a built-in web server that you can use to do so. To run this server, use:python manage.py runserver

Now open your browser and load http://127.0.0.1:8000/ to view your project. You should see some boiler-plate text about “your first Django-powered page”. Although not very interesting to look at, we are making progress! By the way, you can stop the server running by pressing Ctrl+C.

The admin interfaceWith our database created, let’s now get some data into it. In other web frameworks, this would result in an ugly descent into writing reams and reams of complex and error-prone SQL. Alternatively, this may have involved us using a third-party SQL front-end such as phpmyadmin. Fortunately, Django avoids all of that nonsense and comes with its own admin interface for managing the database, adding and deleting data, and more. This is built in to your project.

To enable the admin interface, we need to configure a few things. Firstly, we need to configure the URL. Let’s take

Django: Build your first app

Fig 2: Although we are displaying a simple list, you can use any CSS wizardry you like to display your content.

Find out moreIf you want to find out more about Django, be sure to visit the project’s excellent website and read the fantastic documentation. A world of Django is available at www.djangoproject.com

CBN47.django165.indd 135 6/26/13 10:52 AM

Page 12: Coding sampler

Get online…… and get more from Linux Format!

www.linuxformat.com

Download complete issues of the magazine Grab the latest LXFDVDs via BitTorrent Get new issues as soon as they go to press!

Get help from other readers Discuss the latest Linux news Read articles from previous issues Follow the Team LXF blog Or just pop in for a chat!

Don’t miss our podcast: www.tuxradar.com

Subscribe to Linux Format and get exclusive extras:

Hear the Linux Format team chew over the

hottest topics in free software!

TuxRadar

CBN47.tuxradar_ad.indd 162 6/27/13 11:50 AM

9000