Tutorial 4: Writing first Django App (Part 1)

Tutorial used: https://docs.djangoproject.com/en/dev/intro/tutorial01/
What is covered:
1) Creating a new Django Project
2) Setup sqlite Database for the project
3) Create a new Django WebApp
–a) Create a blank Django App from template
–b) Create Models
–c) Activate Models (a.k.a Create Database)
–d) Editing Models to display unicode
4) Playing with interactive Python shell (using Database API )
–a) import models
–b) create objects
–c) save objects to db
–d) retrieve objects
–e) filter objects
–f) get objects
–g) delete objects
5) Writing a simple custom method

This tutorial can be used without PyDev actually. I would think it is good practice to learn how to work with Django from command prompt as a foundation before moving on to creating Django apps from within Eclipse. So for this tutorial we will be mostly working with “Terminal” command line, while using Eclipse as code editor whenever necessary.

So for my first django app, I am going to create a basic poll web app with a public site and an admin site.

To create a project, I will need to do the following:

1) Create a new project folder with basic configuration files:

Use ( django-admin.py startproject mysite ) to create a “mysite” directory in the current directory.

Screen Shot 2012-12-28 at 11.01.54 AM

The folder we created has a few important components:
mysite/: outer mysite/ directory does not matter, inner mysite/ directory is the python package name used to import anything inside it (e.g. import mysite.settings)
manage.py: (together with django-admin.py) used for administrative tasks like “running the server [python manage.py runserver] “. <Read more>
– mysite/__init__.py : empty file that tells python this directory is a python package. can also be used to execute initialization code. <Read more>
– mysite/settings.py : settings for this django project <Read more>
– mysite/urls.py : url declarations here. it’s like a “table of contents” for your site. Uses the concept of “Cool URIs don’t change by Tim Berners-Lee” <Read more>
– mysite/wsgi.py : an entry point for wsgi(python standard for web servers and apps)-compatible webservers to serve your project. I have not idea what that means for now… <Read more>

Verifying the setup with (python manage.py runserver) I got a successful project folder set up:

Screen Shot 2012-12-28 at 12.46.57 PM

The server can be found in either (http://localhost:8000) or (

The “” represents the IP, “8000” is the port. The configure a different IP or port:

Screen Shot 2012-12-28 at 12.50.51 PM

2) Setup Database

Setting up the database involves editing mysite/settings.py. Because we are only working with a developmental database (and working with sqlite), there is very few configurations that need be done:

Screen Shot 2012-12-28 at 1.14.28 PM

Note that at this point, the sqlite3.db file does not exist yet. It will be created in the next step. We also changed the timezone. ( Note that in the future, when developing a production database, we need to learn how to configure a MySQL or PostgreSQL before this step).

This process configures the database to contain the apps listed in INSTALLED_APPS at the bottom of the settings.py file:

Screen Shot 2012-12-28 at 1.19.07 PM

Now that we are done. Remember to save this file. We are going to synchronize the database now. Go to the folder with “manage.py” and type: ( python manage.py syncdb )

Your database will be automatically set up with the INSTALLED_APPS. If its your first time, terminal will also prompt you to set up a superuser. I did that, not sure how it’s useful yet.

Now to check that the database has been setup, you could run sqlite using ( sqlite3 sqlite3.db )

Screen Shot 2012-12-28 at 1.24.37 PM

3) Creating and Activating Models

This is rather interesting to read before continuing:

Screen Shot 2012-12-28 at 1.30.44 PM

Screen Shot 2012-12-28 at 1.31.38 PM

Not sure how Python path can be manipulated or if Django will automatically configure python path to point to the apps. But we will find out in the future.

So to create a new app, type ( python manage.py startapp polls )

Screen Shot 2012-12-28 at 1.38.12 PM

Interesting read:

Screen Shot 2012-12-28 at 1.39.25 PM

So here we attempt to understand what the components of an App does:

models.py: describes the fields, behavior, and relationship of your data
 tests.py: ?
views.py: ?

We will Create 2 models by editing the “models.py”: Poll and Choice and associate each choice to a poll. This is done using the standard structure:

class <className>(models.Model):
<fieldName> = models.<fieldType>(<modelTypeAttr>)

Link is provided to see documentation on fieldType references

Screen Shot 2012-12-28 at 3.46.06 PM

Note here: interestingly django allows “human-readable name” to be used in place of machine-readable “variables”. See the class “Poll.pub_date” – “date published” is now established as it’s human-readable name which can be used in some introspective part of django.

Note also: relationships are established using “models.ForeignKey“, to link a poll to a choice.

Next, we will Activate the models. Django will automatically:
– create a database schema (i.e. CREATE TABLE statements)
– create python database access API to access your Model objects

This can be done by (1) editing the “mysite/settings.py” file to include the new app:

Screen Shot 2012-12-28 at 4.12.15 PM

(2) sneak peak at what django would do with SQL using ( python manage.py sql polls )

Screen Shot 2012-12-28 at 4.15.03 PM

This may seem counter-intuitive on first glance, that the link is located in choice, not polls. But it makes sense because 1 poll can have >1 choices, hence each choice must have a link to 1 poll:

poll 1 <——— choice 1
<——— choice 2
poll 2 <——— choice 1
<——— choice 2
<——— choice 3

Other commands include:
– python manage.py validate
– python manage.py sqlcustom polls
– python manage.py sqlclear polls
– python manage.py sqlindexes polls
– python mange.py sqlall polls

(3) Run syncdb to create the models (python manage.py syncdb)

Screen Shot 2012-12-28 at 4.33.43 PM


So far we see that manage.py has helped us:
– runserver
– syncdb
– startapp

Now let’s learn how to work with the django database API:

To invoke the Python shell use: ( python manage.py shell ) and this starts the python interactive shell with django. Detailed database API can be used to:
– Import models: Screen Shot 2012-12-28 at 4.48.09 PM
– Create objects: Screen Shot 2012-12-28 at 4.48.14 PM
– Save objects to database: Screen Shot 2012-12-28 at 4.48.27 PM
– Retrieve objects: Screen Shot 2012-12-28 at 4.48.48 PM
– Retrieve all objects using ‘<className>.objects‘: Screen Shot 2012-12-28 at 4.49.05 PM
– Filtering retrieved results:
Screen Shot 2012-12-28 at 5.01.39 PM
– Get individual objects from db: Screen Shot 2012-12-28 at 5.01.53 PM
– Delete objects
Screen Shot 2012-12-28 at 5.22.58 PM

Here we will also learn how to use the __unicode__() method to make models more readable:

Screen Shot 2012-12-28 at 4.51.44 PM

We will also write a custom method in the Poll class to return recently published polls. Here we get a code like this:

Screen Shot 2012-12-28 at 4.59.17 PM

Note that playing with the interactive python does do persistent changes to our database. So going back to our shell we continue with the other part of testing the models:
– The Polls in the database are shown in unicode and readable now!
– We also learn how to perform filter of the fields in a class using “__” e.g.:
Screen Shot 2012-12-28 at 5.08.53 PM
Screen Shot 2012-12-28 at 5.09.01 PM
Screen Shot 2012-12-28 at 5.21.11 PM

– We tested our custom method and it worked
– We learn how to use _set (selects all choices linked to it) to link >1 choices to 1 poll:
Screen Shot 2012-12-28 at 5.13.39 PM
– We learnt that you have API access to 2 objects that are related from each of them:
p                         c 
c.poll                 p.choice_set.all()
poll 1 <——— choice 1
<——— choice 2
<——— choice 3

Now we are done with playing with Database API. More practice will be needed before I can really be familiar with using the API to handle the database. TO COME BACK FOR MORE PRACTICE…

This entry was posted in Tutorials. Bookmark the permalink.

One Response to Tutorial 4: Writing first Django App (Part 1)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s