Changed!

Okay, putting only technical things into a blog is actually boring. So from now on, I will post everything on this blog. Not really everything actually, since I have another blog. I will also use Bahasa Indonesia here.

In short, more general and.. bilingual! :v

Advertisements

Templating

Yes, this article is still about Django. In this short article, I will explain about templating. Django uses a templating language that differs from Python itself. Why? Because, this language is intended for web designers. Thus, web designers don’t have to understand “real programming” with Python. And also this is also useful to make clear difference between application logic and user interface. With this simple templating language, Django can prevent developers from using too much programming logic in a template.

Things you should remember about this templating language are:

  1. The language is PURELY for displaying data
  2. You can’t declare variables or functions in a template
  3. Operators are basic and limited
  4. Only support basic programming logic like looping or operator
  5. The language consists of template tags, template filters,  and context variables
  6. Template tags are in {% %} bracket. Examples: {% for %}, {% endfor %}
  7. Template filters are for simple data processing, like formatting or basic computation. Filters are identified by “|”. Examples: users|last, users|element:5
  8. You can define custom template tags and template filters
  9. Variables in a template are called context variables
  10. You can define context processors in each Django app. Context processors are like “pre-loaded” context variables that will be loaded every time a template being rendered. This is perfect for displaying data that must be displayed on every page. Examples: is_logged, username

Another interesting thing about templating in Django is: template inheritance. Template inheritance is powerful for layouting your template. You can define a basic layout containing header, content, and footer called layout.html. Then you can create a template that extends layout.html, with different content than another template which is also extending layout.html. In short, those two templates have same layout, but different content. Thus, you don’t have to write header & footer on every template.

For example, this is the layout.html


<html>

<head><title>Title</title></head>

<body>

    {% block header %}

        This is header

    {% endblock %}

    <div class="content">

         {% block content %}

         {% endblock %}

    </div>

    {% block footer %}

        This is footer

    {% endblock %}

</body>

</html>

And this is a template that extends layout.html (page1.html):


{% extends "layout.html" %}

{% block content %}

    This is content of page 1

{% endblock %}

So, page1.html will display a complete web page with “This is content of page 1” as the content.

Simple and pretty neat :p

Model Inheritance

Model Inheritance is one of the interesting features of Django. With this feature, you can define “base” models to be extended. For example, you may want to create some models that have timestamp or “logical delete” attribute (i.e is_deleted). Defining timestamp & is_deleted attributes in every model would be time-wasting. So, in Django you can define abstract models.

Abstract models are different with ordinary models. When syncdb command is executed, Django will not create database tables for those abstract models. Django will only create database tables for  explicit models that extend abstract models. This is useful. Very useful. Take a look at these code for example:

This is an abstract model.

#file: blog/core/models.py

from django.db import models

import datetime

class BaseModel(models.Model):

    timestamp = models.DateTimeField(auto_now_add = True)
    is_deleted = models.BooleanField(default = False)

    def save_upd(self):
        self.timestamp = datetime.datetime.utcnow()
        self.save()

    def delete_soft(self):
        self.is_deleted = True
        self.save_upd()

    class Meta:
        abstract = True

This is an example of a model that extends BaseModel.

#file: blog/user/models.py

from blog.core.models import BaseModel

class User(BaseModel):
    id_user = models.AutoField(primary_key = True)
    username = models.CharField(max_length = 200)
    password = models.CharField(max_length = 128)

    class Meta:
        db_table = 'user'

With that, User model will have id_user, username, password, timestamp, and is_deleted as attributes. That’s all. Very simple & useful, indeed.

How Django Works

We already know that Django is a web framework. But now, how it works? It’s useless if you randomly develop a Django application without understanding about its concepts. The first question is: Where should I start?

To answer that question, let’s take a look about a Django application’s request flow:

web browser address bar -> urls.py -> views.py -> models.py -> database

As stated on Django documentation, a Django project consists of applications. Each of application has Python modules. Each Python module has classes or functions. The structure is like this:


Project_Name
    templates
        app1
             index.html
        app2
             index.html

    App1

        models.py

        views.py

        urls.py

    App2

        models.py

        views.py

        urls.py

    settings.py

    urls.py

You can place the templates folder outside or inside the apps, depending on your TEMPLATE_DIRS on settings.py.

So, the answer is, start with settings.py, and then urls.py, models.py, views.py, and the last is templates. Django will first check settings.py file to verify that your Django project is configured properly. After that, Django will dispatch request on urls.py. That urls.py contains URL Patterns that constructed in regex (Regular Expression). For example:

#urls.py
from django.conf.urls import patterns, url
from blog.news import views

urlpatterns = patterns('',
    url(r'^news/(?P<id_news>\d+)$', views.news, name='news'),
)

That URL Pattern will dispatch HTTP Requests and reply with HTTP Responses from views.news() function.  The function will return News with id = id_news, and then render a template to display data. For example, if you used localhost:8000 as your host & port, url http://localhost:8000/news/3 will display a page containing a news with id = 3.

What is inside that views.py module? For example, here it is:

from blog.news.models import News
from django.shortcuts import render_to_response
from django.template.context import RequestContext, Context

def news(request, id_news)
    news = News.objects.get(id_news = int(id_news))
    context = Context({
       'news':news,
    })
    return render_to_response('templates/news/view.html', context, context_instance = RequestContext(request))

You can see that views.py get data from blog.news.models module a.k.a models.py file, right beside views.py. This is how models.py file looks like:

from django.db import models

# Create your models here.

class News(models.Model):
    id_news = models.AutoField(primary_key = True)
    text = models.TextField()
    timestamp = models.DateTimeField()

    class Meta:
        db_table = 'news'

That models.py file of course, get data from database via Django’s built-in ORM (Object-Relational Mapping). You can define the table name with Meta class, and the column names are exactly the same as News class properties.

Pretty simple, right? Those are just basic concepts, I will explain concepts of templating later. Once you know about these basic concepts, getting started with Django will be easy. Hope this helps 🙂

Installing Django

What is Django? Django is a powerful and fully-customizable web framework written in Python. Some websites like Instagram used it. Django  has a rather unique concept: MTV (Model-Template-View), unlike most web frameworks. As you can see, there is no “controller” in Django. Django provides “View” to help developers implementing the controller’s jobs. “View” is the place for retrieving data from “Model” to be displayed on “Template”. What is “Template”, anyway? Templates are simply the front-end component. They used a templating language, a language that differs from Python itself. It is very simple, with basic programming logic like operator or loop. For example, you can make HTML files as templates, with template language on them.

So now, how to install Django? Quite simple. The steps are just simply:

  1. Install Python
  2. Install pip
  3. Install Django

Installing Python

Installing Python is very simple. But which version? I recommend version 2.7 since it worked perfectly on running Django.

On Windows, you can get the installer from here.

On ubuntu, you can run these commands:

sudo apt-get update
sudo apt-get install python2.7

Once Python have been installed, you can install “pip” now.

Installing pip

Pip is a tool for installing and managing Python packages, including Django. Installing pip on ubuntu is very simple, just run this command:

sudo apt-get install python-pip

For windows, first you must add these paths into your environment variables “PATH”:

C:\Python27\
C:\Python27\Scripts\

And then, run python-distribute script to install easy_install

python distribute_setup.py

Install pip with easy_install

easy_install pip

Installing Django

The command for installing Django with pip is very simple:

pip install django

To install Django with specific version, run this command:

pip install django==1.4.2

You can replace 1.4.2 with any Django version, such as 1.3.1 or 1.5.0.

Remember that you must use sudo for installing python packages with pip on UNIX-based operating systems.

Verify Django Installation

To make sure if Django is properly installed, you can simply import Django and then view the version, like this:

$ python
>>> import django
>>> django.VERSION
(1, 4, 2, 'final', 0)

Congratulations! Now you can start making your Django projects!

Hello World!

It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet.