“Hello world!”application in Django
Django project is collection of applications. To create application inside of the project, usemanage.pywith following syntax:
(env) $ ./manage.py startapp hello
This command will create application (Python package)with the namehelloin the root directory of the project.
Application structure
Structure of an application is represented as Python package too. It’s directory structure after creation is following:
(env) $ tree hello
hello/
├── admin.py
├── __init__.py
├── models.py
├── tests.py
└── views.py
These files are:
The
__ init__.py
file defines a package. Python needs it to differentiate between the standard folders and the packages.The
admin.py
file contains the models that need to be incorporated in the administration module.The
models.py
file contains all the models of our application. Models allow us to create our database and store information.The
tests.py
file contains the unit tests of our application.The
views.py
file can contain views. This file will contain all the actions before sending the HTML page to the client.
Installing application
We have to install newly created application to the web site. The list of installed application is located in the file settings.py
in the tuple INSTALLED_APPS
. To install new application, add the name/path of new application to the list (‘hello’). The rest keep unchanged.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello',
)
Simple routing
We have to design the url API, where will be new application located. The urls are defined in the urls.py
file in the variable urlpatterns
. If we want to associatehello applicationto the url '/helllo'
, insert the following line to the urlpatterns
variable:
url(r'^hello$', 'hello.views.greetings'),
The function url()
has two params (5, but these two are mandatory):
regex- URL specification as regular expression (
http://127.0.0.1/hello
)view- view to handle given URL (apphello, filename
views.py
and functiongreetings()
)
Associating view with the URL
According to the created URL in theurls.pyfile, we have to create function greetings()
inside of the views.py
file in created helloapplication. The content of the function will be very easy - it just returns the"Hello world!"string as a HTTP response over HttpResponseobject
:
from django.shortcuts import HttpResponse
def greetings(request):
return HttpResponse("Hello world!")
Testing the result
To test, if everything is ok, run the server and visit the local URL http://127.0.0.1/hello
(env) $./manage.py runserver
Validating models...
0 errors found
August 10, 2014 - 11:57:33
Django version 1.6.5, using settings 'mysite.settings'
Starting development server at
http://127.0.0.1:8000/
Quit the server with CONTROL-C.**
Rendering template
Django comes with own templating system. To create template for our application, create subdirectory templates/
inside, so Django templating system can find templates easily:
(env) $mkdir mysite/hello/templates
Create simple template:
<html>
<head>
<title>Hello world</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Update thegreetings()function to render template withrender()function:
defgreetings(request):
returnrender(request, 'hello.html')
Save and reload/rerun server to see the result.
Modify template to add tag into it instead static text:
<html>
<head>
<title>Hello world</title>
</head>
<body>
<h1>Hello {{name}}!</h1>
</body>
</html>
And update view:
defgreetings(request):
returnrender(request, 'hello.html', {'name':'johny'})
Save and reload/rerun server to see the result
Advanced routing
Let’s modify our app to be able to say hello to someone, who will be specified from the URL path. So, if the path will be '/hello/johny'
, the app will render our template with the johny as parameter.To capture a value from the URL, just put parenthesis around it.
Add new URL to the project’surls.py
file:
url(r'^hello/(\w+)$', 'hello.views.greetings'),
Update the greetings()
function in your app’s views.py
file:
from django.shortcuts import render
def greetings(request, name):
return render(request, 'base.html', {'name': name})
Modify urls.py and views.py
in following way:
if URL is plain'hello', render text‘Hello world!’
if URL is in the form'hello/NAME', render text‘Hello NAME!’
Update URL
url(r'^hello/(/(?P<name>\w+))$', 'hello.views.greetings'),
Update the greetings()
function in your app’s views.py
file:
def greetings(request, name=None):
if name is None:
name = "world"
return render(request, 'base.html', {'name':name})
Exercise
Extend the app to greet someone based on his surname ('hello/john/rambo')
Extend the URL with the list of names ('hello/john/jack/bilbo/lucy')
Application’s urls.py file
In the case of creating own application, it is good practice to create application basedurls.pyfile inside of the application package. In the case ofhello applicationit is about extracting all URLs related with hello application and save it inhello application’spakage:
from django.conf.urls import patterns, url
urlpatterns = patterns('hello.views',
url(r'^(/(?P<name>\w+))?$', 'greetings'),
)
The remaining line in the project’surls.pyfile only contains line for including the application’s URLs:
url(r'^greetings', include('hello.urls')),
Installation of debug toolbar application
Install debug toolbar application to your environment, which helps you to debug your project.
(env) $pip install django-debug-toolbar
Add it into your installed applications in project settings.py
(Quick setup):
'debug_toolbar',
Restart/reload server, point your browser to your rendered template, play with debug toolbar and inspect the template.
Create requirements file
Create requirements file from current state of environmnet and try to create new with installation of all packages from requirements file.