Django Tutorial – Simple Notes Application

February 9th, 2010

Django is a great web framework, so easy to fall in love.

Before starting this tutorial, you need to install Django framework.

This tutorial assumes you have basic knowledge in Django, such as Model, View and Template. If not so, you can start with tutorials in Django documentation.

Let’s start by creating new project :

django-admin.py startproject webnotes

It will create directory with 4 files inside : __init__.py, manage.py, settings.py and urls.py

Setup our project configuration by editing settings.py. We’ll use sqlite for our example.

DATABASE_ENGINE = 'sqlite3' 
DATABASE_NAME = 'webnotes.db'

Create new directory under webnotes to save our templates :

cd webnotes
mkdir templates

Point template directory to our template directory that has been created earlier. You can use full path to your templates directory, but using relative path is recommended, so you won’t need to change it when deploying to the web server.

import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
 
TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates')
)

In Django best practice, one website is built by several applications that work together. For this simple web, we only create one application called notes.

django-admin.py startapp notes

The command create application named notes with 4 files inside : __init__.py, models.py, tests.py dan views.py

Open models.py, then add our Notes model :

1
2
3
4
5
6
7
8
9
10
from django.db import models
 
class Notes(models.Model):
    """Model to save our note"""
    title   = models.CharField(max_length=255)
    content = models.TextField()
    #automatically add timestamps when object is created 
    added_at = models.DateTimeField(auto_now_add=True) 
    #automatically add timestamps when object is updated
    last_update = models.DateTimeField(auto_now=True) #

To see all available field, you can consult Django documentation.

Open views.py and let’s create some views using django generic views, and add this following lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from django.views.generic.list_detail import object_list
from django.views.generic.list_detail import object_detail
from django.views.generic.create_update import create_object
from django.views.generic.create_update import update_object
from django.views.generic.create_update import delete_object
from django.core.urlresolvers import reverse
 
from models import Notes
 
def notes_list(request):
    """Show all notes"""
 
    return object_list(request, 
        queryset=Notes.objects.all(),
        template_name='notes/list.html',
        template_object_name='note'
    )
 
def notes_detail(request, id):
    """View note detail based on note id"""
 
    return object_detail(request,
        queryset=Notes.objects.all(),
        object_id=id,
        template_name='notes/detail.html',
        template_object_name='note'
    )
 
def notes_create(request):
    """Create new noew"""
 
    return create_object(request,
        model=Notes,
        template_name='notes/create.html',
        post_save_redirect=reverse("notes_list")
    )            
 
def notes_update(request, id):
    """Update note based on id"""
 
    return update_object(request,
        model=Notes,
        object_id=id,
        template_name='notes/update.html',
        post_save_redirect=reverse("notes_list")
    )            
 
def notes_delete(request, id):
    """Delete a note based on id"""
 
    return delete_object(request,
        model=Notes,
        object_id=id,
        template_name='notes/delete.html',
        post_delete_redirect=reverse("notes_list")
    )

Create urls.py in our notes application, and add this lines :

1
2
3
4
5
6
7
8
9
10
11
12
from django.conf.urls.defaults import *
 
import views
 
urlpatterns = patterns('', 
 
    url(r'^list/$', views.notes_list, name='notes_list'),  
    url(r'^detail/(?P<id>\d+)/$', views.notes_detail, name='notes_detail'),  
    url(r'^new/$', views.notes_create, name='notes_create'),  
    url(r'^update/(?P<id>\d+)/$', views.notes_update, name='notes_update'),  
    url(r'^delete/(?P<id>\d+)/$', views.notes_delete, name='notes_delete'),  
)

Edit settings.py to install our application by registering the application name to INSTALLED_APPS.

...
INSTALLED_APPS = (
    ...
    'notes'
)
...

Add urls in our notes application into main url in our project (webnotes/urls.py)

1
2
3
4
from django.conf.urls.defaults import *
 
urlpatterns = patterns('',
    (r'^notes/', include('notes.urls')),

Use this command to create our tables :

python manage syncdb

To run the development server, you can use this command :

python manage runserver

We can try this application at http://localhost:8000/notes/list/
You can download all source code at github.

Related posts:

  1. Handling 404 Page on FeinCMS
  2. A Quick Tutorial on Django MPTT
  3. Receiving Email Using AppEngine and Django
  4. CodeIgniter Tutorial – To do list application#2
  5. Using django-paypal IPN in Django 1.2

Tags:

7 Comments