Django Hello World

This post is part of my Django series. You can see an overview of the series along with instruction on how to get all the source code here.

Prerequisites

This article assumes that you have Django installed and configured correctly. You can check that Django is installed correctly with the following command a a terminal window.

$ python -c "import django; print(django.get_version())"

If Django is not installed please see the official installation notes. I would recommend using virtualenv.

Note: ensure that the python alias command is pointing to the right python version. Python 3.4 and 2.7 come shipped with my Linux box by default with the python alias pointing to 2.7. To save any potential breakages from updating the alias I simply run python3.4; the tutorial refers to the command python amusing it is pointing to the required version of python for your Django installation.

$ which python

What is Django?

Django is a MVT (MVC) web development framework for the Python programming language.

Similar to MVC the MVT or Model View Template design pattern uses templates as views and views as controllers.

Creating a Project

A Django website consists of a Project and one or more Apps. A project contains the configuration such as settings and URL routing config while Apps contain code which render HTML to the user.

To create a project open a terminal and CD into the directory which you want to create your project and run the following:

python django-admin startproject DjangoSandBox

Django has now created a default project set-up which resembles something like this:

DjangoSandBox/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

These files are:

  • manage.py: The Django command program; we use to create applications, make migrations, run the developer server and many other things
  • settings.py: The settings file for the project
  • urls.py: The URL routing config for the project
  • wsgi.py: Used for WSGI-compatible web servers

Read more about startproject.

Django comes preconfigured for database access with SQLite3. You can use other database vendors but we will assume SQLite3 is good enough for your development process.

Django is modular and comes preconfigured with some default Django apps contained within the INSTALLED_APPS list of settings.py. Some of these have tables which need to be generated and populated. We can do this with the following command.

python manage.py migrate

The above command will also create the database file if none is found. A db.sqlite3 file should now be generated and placed within the project directory.

You can read more about migrate.

Django comes shipped with a light weight development web server. To run the development web server run the following command:

python manage.py runserver

You should see something similar to:

Performing system checks...

0 errors found
July 08, 2015 - 15:50:53
Django version 1.8, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C

You can enter http://127.0.0.1:8000/ into a web browser and you will see the default web page. Read more about runserver.

Creating An Application

A project is a collection of settings, an app contains code which generates the html.

You can have apps anywhere on the Python path though lets keep things simple and create them inside the DjangoSandBox project directory. In a terminal cd into the directory which contains the mange.py file and run:

python manage.py startapp helloworld

You should see something similar to the following generated:

helloworld/
    __init__.py
    admin.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

All apps need to be added into the settings.py file; add helloworld into the INSTALLED_APPS LIST to resemble something similar to this:

# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'helloworld'
) 

Hello World With HttpResponse

We are going to create a ‘hello world’ application which returns a hello message to a user. We can do this by returning an instance of a HttpResponse from a function with our hello message passed in.

# helloworld/views.py
from django.http import HttpResponse

def hello(request):
    return HttpResponse("This would be the hello world example!!!")

The function above is a view function; i.e. the V of our MVT design template. The code should be placed within the views.py file of the helloworld application.

The request object is the HTTP request sent to the web server from the user. We don’t currently need anything from this.

URL Routing Config

Now we have our view function we need to be able to call it. Django will automatically call this as long as we register it against a URL. We do this with URL routing config.

Our project and our app both contains urls.py file; these are the URL routing config.

We would like to register our function to http://127.0.0.1:8000/helloworld/hello. Django strips off the protocol, domain and ports of the URL along with the first /. It also will append a trailing / if one is not found.

As far as we are concerned for our routing config our URL is helloworld/hello/

By default the urls.py in the project is called, yet we would like our routing to be passed into the urls.py of our app. A good approach is to search the URL for helloworld/ within the project config and then pass control onto the app urls.py which will search for hello/. Note the matching helloworld/ is stripped from the URL when entering into the helloworld/urls.py.

Our code will look like this:

#helloworld/urls.py
from . import views

urlpatterns = 
    patterns('',
             url(r'^hello/$', views.hello, name="hello"),
             )

We register routing as an instance of URL into the patterns function:

  • r’^hello/\$’: this is a regular expression matching our partial hello/ url. ^ denotes start and $ denotes end. The r infront of the string denotes a raw string; it is taken as is regardless if any escape characters are found.
  • views.hello: this is the view function
  • name=”hello”: this is the name of the url. We can refer to this along with the namespace (see below) to generate this url

The following registers the helloworld/ URL within our project urls.py:

# DjangoSandBox/urls.py
rom django.conf.urls import patterns, include, url

from helloworld import urls as helloworld_urls

urlpatterns = 
    patterns('',
             url(r'^helloworld/', include(helloworld_urls, namespace="helloworld")),
           )
  • r’^helloworld/’: matches any URL which starts with helloworld/ including our helloworld/hello/
  • include(helloworld_urls): passes in all our URL routing config from our hellworld/urls.py
  • namespace=”helloworld”: this is the namespace of all helloworld routing config. Our URL named hello can be refered to as helloworld:hello.

You can now run the development server and navigate to the following to test.

http://127.0.0.1:8000/helloworld/hello

You can read more about url config.

Template Loader & Request Context

The example above only uses the V of our Model View Template design pattern. We are now going to hook in some model data (context) along with a template (html).

Add the following into helloworld/views.py

#views.py
from django.http import HttpResponse
from django.template import loader, RequestContext
from django.utils import timezone

def with_template_loader(request):
    template = loader.get_template('helloworld/template_example.html')

    context = RequestContext(request, {'who': "Obelix", 'when': timezone.now(), 'islong': True})

    return HttpResponse(template.render(context))

The above locates and loads our template “helloworld/template_example.html” and then passes in our data of who/when into the a RequestContext. We then use the template to render the html using the RequestContext and return the result via a HttpResponse.

Add the following template code into helloworld/templates/helloworld/template_example.html. We use the extra directory called helloworld within the helloworld application as a way of name spacing our templates; otherwise using a template called index.html could use any index.html from any application as it will match the first found entry.

<!-- helloworld/templates/helloworld/template_example.html -->
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>Hello World With Template</h1>

<p>Hello there {{ who }}!!! </p>

<p>It is{{ when }} </p>

<p>
    {% if islong %}
        This is the long way around!
    {% else %}
        This was taken with a shortcut!!
    {% endif %}
</p>
</body>
</html>

A template is simply html mixed with special control logic. We will explore templates in more detail later on but for now just appreciate that

  • Our context data is passed to the template; each key is available as a template variable
  • We can use if else and endif logic between {% %}
  • We can output a value into the html between {{ }}

We can then hook our new view into the URL config with the following.

#helloworld/urls.py
from . import views

urlpatterns = 
    patterns('', 
             url(r'^template_loader/$', views.with_template_loader, name="loader"),
             )

You can now run the development server and navigate to the following to test:

http://127.0.0.1:8000/helloworld/template_loader

Render

We can reduce the amount of work in the previous example by calling render from django.shortcuts. This takes the template name, the context dictionary and the request object.

#views/urls.py
from django.shortcuts import render
from django.utils import timezone

def with_template(request):
    context = {'who': "Obelix", 'when': timezone.now(), 'islong': False}
    return render(request, 'helloworld/template_example.html', context)

We can hook this into our URL config with the following:

#helloworld/urls.py
from . import views

urlpatterns = 
    patterns('',
             url(r'^template/$', views.with_template, name="template"),
             )

You can now run the development server and navigate to the following to test.

http://127.0.0.1:8000/helloworld/template

Referece:

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s