Been learning a new web framework since I had time on my hand last month. I thought I'd get started on web development since this seems to be where the action is headed in the near future (mobile apps look good too but couldn't afford those toys so I'm sticking with something more 'freebie').
Two of the most popular web framework in the scene are Ruby on Rails and Django. RoR is out, since I'm not keen to learn a new language just so I could try the latest/greatest web frameworks. Fortunately, Django was built on top of Python, so it was really more of applying my rudimentary python skill into another domain.
Looking for Django tutorial/howtos, I found the online version of "The Definitive Guide to Django" here which is probably the best intro for Django. 'been playing around with it and I thought I'd create own quickie reference material that I can quickly jump into without reading the voluminous manual.
Part 1: Introduction
Django is a web framework, basically what it does is do most of the grunt work of web development and provide you with plenty of abstraction (or shortcuts) to most common and frequently done task when developing web apps. For instance, you can use Django's authentication module for authenticating your web users rather than cobbling something amateurish on your own.
Django follows the MVC (Model-View-Controller) philosophy which implement a strict separation of different parts of the application (aka loose coupling) which makes it easy to change parts of the code without impacting other parts of the application. However, in Django they call it MTV (Model-Template-View). Model is your database setup while Template is generally your presentation layer (ie. html/ajax) of your web app and View is your "business logic layer" and binds your model and template.
Part 2: Installation and Setup of Django
Step 1: I use Fedora, open your terminal, go to root and run the following:
yum -y install Django mysql MySQL-python
rpm -q Django mysql MySQL-python
Step 2: Start a Django projet
mkdir ~/djcode #This is where your Django code will live
cd ~/djcode
django-admin.py startproject mysite #Create the appropriate config files
cd mysite
python manage.py runserver& #Run the development web server
firefox http://127.0.0.1:8000 #Test your Django setup
You should now have working Django setup and ready for your web development
Part 3: Simple Django Web Application
Let's create a simple web page to illustrate how Template and View (in MTV acronym) works.
Step 1:
Create a template directory where you'll place all your html files.
mkdir Templates
Step 2:
You need to tell Django where to find your templates. In your ~/djcode/mysite/settings.py find the TEMPLATE_DIRS settings and add the following:
TEMPLATE_DIRS = (
'/home/gene/djcode/mysite/Templates',
)
Step 3:
Go into the Template directory (ie. "cd Templates") and create a file named basic.html:
The "{{ nickname }}" and the "{{ date }}" inside the html file indicate that these are variables that will be defined when you 'render' this template.
Step 4:
We now need to create a view. Remember that view describe which data you see and not how you see your data. View process that data before it is presented. So in the ~/djcode/mysite directory, create the view.py file:
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
name = 'Gene Ordanza'
now = datetime.datetime.now()
return render_to_response('basic.html', {
'date': now,
'nickname': name })
If you're fairly new to web framework and not coming in from programming background, render_to_response is the tricky part. Both 'nickname' and 'date' in the basic.html are variable and so is the 'name' and 'now' in the view.py. What view.py does is call the template (in this case basic.html) through render_to_response method and then defined the variable inside. Remember: separation of different part of your web app is what you're after. So your web designer or web developer are free to mess around with their respective area of expertise without messing other parts of your application.
Step 5:
You now have to map your template to your view. Now this is where your URLconf comes in. URLconf file is something like table of contents for your web app. Basically, you go to URL address then your Django framework will map that URL to a view you've define. In turn, your view will call your template. That in essence is how your Django works in the background.
In the ~/djcode/mysite/urls.py file, add the following:
from mysite.view import current_datetime
urlpatterns = patterns(' ',
(r'^time/$', current_datetime)
)
Also, in ~/djcode/mysite/settings.py file, look for the TIME_ZONE variable and change it to whatever appropriate time zone for you. In my case, that's TIME_ZONE = 'Asia/Manila'. Voila! That's it, point your browser to the following address http://127.0.0.1:8000/time.
Part 4: Configure Database
One of the core feature of Django is ORM (Object-Relational Mapper) and this is where most web frameworks really shines. Basically, ORM enables you to link your data models in Django to the actual database (in this case MySQL). Loosely defined, our data models refer to your database tables. With Django's model, you don't have to get down and dirty with database access. Most of the data retrieval and manipulation can be done within Django as it provide a nice abstraction to your database application. For our web app, we'll create a book/author/publisher database.
Step 1:
Setup your MySQL server
service mysqld start
mysqladmin password #setup your password
mysqladmin -u root -p create testdb #create the testdb database in MySQL
Step 2:
In your ~/djcode/mysite/settings.py file, add the following:
DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'testdb'
DATABASE_USER = 'root
DATABASE_PASSWORD = 'hello' #Or whatever password you've set
Step 3:
You now need to create an app where you model and views will reside for that application.
cd ~/djcode/mysite
python manage.py startapp books
Step 4:
The command above should create a subdirectory called ~/djcode/mysite/books. Inside that directory, edit the file models.py and add the following:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
city = models.CharField(max_length=50)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=30)
website = models.URLField()
def __unicode__(self):
return self.name
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __unicode__(self):
return self.title
Step 5:
At this point, the testdb database is still empty. We've defined 3 models (Publisher, Author, Books) that correspond to your database tables (that we haven't created yet). We need to activate these models to create the actual tables. In the settings.py file, find the INSTALLED_APPS setttings and comment out the five default apps enabled there (ie. 'django.contrib.admin') by prepending a '#' before the app name. And then add the 'mysite.books' app in the INSTALLED_APPS, so it should look like this:
INSTALLED_APPS = (
# 'django.contrib.auth',
# 'django.contrib.contenttype',
# 'django.contrib.sessions',
# 'django.contrib.sites',
# 'django.contrib.auth',
'mysite.books',
)
In the MIDDLEWARE_CLASSES comment out the middleware apps as well.
Step 6:
The 'mysite.books' is the web app that we're working on. We now need to validate/check our settings, just to be sure that we don't have any typo or illegal settings. In the ~/djcode/mysite directory, run the following command:
python manage.py validate
If no error came up, then you can now commit the Django model to the MySQL database,
python manage.py syncdb
When you run the command above, it should prompt you to also create a root account and password.
That's it! You have now created and sync the following tables: books_publisher, books_author, books_book.
Part 5: Set-up of Admin Site
Like the ORB feature, the Admin Site is one of the core feature of Django and what makes developing web apps for Django easier and more productive. With Admin Site, writing boilerplate code for your web app infrastructure is taken care for you so you can immediately add, change and view content for your web site and avoid getting bogged down with the usual repetitive code of making production-ready interface for your web site.
Step 1:
In the settings.py file, uncomment back the settings for INSTALLED_APPS and the MIDDLEWARE_CLASSES to enable the Admin Site.
Step 2:
Sync your database. The settings that were uncommented above are packages that need to sync to the database. In your ~/djcode/mysite directory, run the following:
python manage.py syncdb
This will prompt you to create a root account for your Admin site.
Step 3:
In urls.py, uncomment the following code for the Django admin:
from django.contrib import admin
admin.authodiscover()
urlpatterns = patterns(' ',
# . . .
(r'^admin/', include(admin.site.urls)),
# . . .
)
Step 4:
Point your browser to the http://127.0.0.1:8000/admin and you should get the following web page:
Step 5:
Try to log in using the root account you've created when you run the "python manage.py syncdb" and you should get the following web pages:
Try to create another account, change their attributes, play around and get comfortable with the Admin Site feature.
Step 6:
We'll now hook our models to the Admin Site by creating the admin.py file in the ~/djcode/mysites/books directory (ie. the books/ directory was created in Part 4). In our admin.py, add the following:
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
Restart your runserver to let the development web server read the file. Go back to your Admin site and log in and you should now see the following:
At this point, you can now add or change data for your Publisher, Author, and Book database. Now, how difficult was that?
Part 6: Creating Forms
To extend our simple Publisher/Author/Book database, we'll create a rudimentary search capability that let users search books by title.
Step 1:
We'll need to create an HTML front-end for the search form. In the Template directory, create a simple html search form.
Step 2:
Create the search view that will call our html search form. In your ~/djcode/mysite/books/view.py file, add the following:
from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
Step 3:
In your urls.py file, map the html searh_form to the Django view.
from mysite.books import view
urlpatterns = patterns(' ',
# . . .
(r'^search-form/$', views.search_form),
# . . .
)
Step 4:
If you try to check the url http://127.0.0.1:8000/search-form, you'll get an error since we haven't yet coded the /search/ view yet. So in your view.py, add the following:
from django.http import HttpResponse
from django.shortcuts import render_to_response
from mysite.books.models import Book
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains=q)
return render_to_response('search_results.html', {'books':books, 'query':q})
else:
return HttpResponse('Please submit a search term.')
Step 5:
We now need to pass the books object to another template called 'search_results.html' that will display our search results. In your Template directory, create the search_results.html:
Step 6:
Now visit http://127.0.0.1:8000/search-form/ and search for both existing and non-existing titles in your database. And that's it!
If you've read this far, then you really ought to read the more concise, better written, in it's original form found here :-) If you have questions though, feel free to submit a comment and I'll try to help out.






