SlideShare a Scribd company logo
An Introduction to Django Web
Framework
David Gibbons
September 2015
Joined Ammeon almost 2 years ago in Porcos team
Previously worked with Django web framework.... and liked it.
Fast development of new features, clean architecture, on top of a fast, stable, secure
framework.
Developed a Django-powered Web Application for energy management
Over 100 users logged in each week to view, analyse their data
Easy to manage user permissions for specific website features
About Me
2
Introduction
Getting Started
Architecture
Other Components
Demo
3
Agenda
Introduction
4
5
6
History
Created at Lawrence Journal-World
newspaper in 2003 in Kansas, USA
Adrian Holovaty and Simon Willison
initially wrote from scratch as nothing
fitted
Historically excellent documentation
Named after French Guitarist Django
Reinhardt
Open sourced in 2005
A high-level Python Web framework that encourages rapid development and clean,
pragmatic design
A free and open source web framework (public repository at https://github.
com/django/django)
Model–View–Controller (MVC) architectural pattern
Don’t Repeat Yourself (DRY) principle
Lots of out-of-the box features
What is Django?
7
8
Django Version History
What is a Web Framework?
9
Software framework designed to simplify your web development life
Handles many of the common operations associated with web development including:
● accessing the database
● creating HTML templates
● managing sessions
Promotes code reuse
Some other popular Python Web Frameworks
10
Flask: micro framework that provides a simple template for web development
Tornado: web framework and asynchronous networking library, noted for high
performance
Bottle: fast, simple lightweight micro web-framework
Pyramid: MVC framework with flexible component choices
CherryPy: mature object-oriented web framework - compact and simple
11
How popular is Django?
PyPI is the official 3rd party package repository for Python
Stats available on number of downloads in last week, month, year.
Django is the most downloaded web framework, is regularly updated by community
Websites using Django
12
Django and LITP
Plugin development similar to developing Django apps:
- Defined directory structure
- Makes use of classes and functions provided by a “core”
- Form validation in Django is similar to LITP plugin validation
- Models and migrations in Django similar to LITP APIs and migrations
13
Getting Started
14
Build a web application to allow the public to vote in polls, and view results
Typical requirement for a online news website (such a Lawrence Journal-World)
Three interested parties:
● A software developer creates the necessary models
● A site administrator creates/updates/deletes the polls
● A public website visitor votes in the polls and views results
Same example application as the official Django tutorial, for more detailed explanation
see https://docs.djangoproject.com/en/1.8/intro/tutorial01/
Polls Web Application
15
1. Django 1.8 needs at least Python 2.7 installed!
2. Create a new project directory, install Django (preferable with pip and virtualenv)
3. To create Django project “mysite” run:
Creates a directory structure which is the base of project:
16
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
$ django-admin.py startproject mysite
Django Quick Start Guide
4. Django supports 4 databases:
Update the settings.py file to use sqlite and ‘Europe/Dublin’.
5. To create the sqlite file and database tables initially needed by Django run:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
TIME_ZONE = 'Europe/Dublin'
17
$ python manage.py migrate
6. Run the built-in Django development server (default port 8000):
7. Open 127.0.0.1:8000 in web browser, and you should see a page saying “It worked!”
18
$ python manage.py runserver
8. A Django “project” is a collection of Django “app”s.
An app is an application that does something specific (blog or poll)
To start our new polls app, cd into ‘mysite’ and run:
This creates the directory structure for your ‘polls’ app:
19
$ django-admin.py startapp polls
polls/
__init__.py
admin.py
migrations/
__init__.py
models.py
tests.py
views.py
Application Quick Start Guide
9. Add polls application to INSTALLED_APPS in settings.py to activate ‘polls’ models
10. Start working on the models, views, urls and templates for the polls app!
20
INSTALLED_APPS = (
...
‘polls’
)
Django Architecture
21
What is MVC (Model-View-Controller)?
Software architectural pattern for user interfaces, popular in web applications.
Other MVC frameworks: Ruby-on-rails (Ruby), ASP.NET MVC (C# or Visual Basic)
Alternative Django-specific acronym is MTV (Model, Template, View) 22
Template - User facing
URLs - URL Configuration
View - Business Logic
Model - Database Table
23
Models
Single definitive source of information about data
Define the interface to the database, an auto-generated database API
Generally maps to a single database table, and each attribute represents a database
field
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
24
Once the models are defined, two commands are run to create the database tables:
Models (continued)
25
$ python manage.py makemigrations polls
$ python manage.py migrate polls
Views
Python function which takes a Web request, and returns a Web response
This response can be HTML for a web page, a redirect, a 404 Not Found error etc.
Contains the logic on what is returned from a particular request
Function-based or class-based
26
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ‘. ’.join([q.question_text for q in latest_question_list])
return HttpResponse(output)
Views (continued)
Often required to return some variables from the model to a HTML template. The
useful ‘render’ shortcut:
Views are also used to check that a user is logged in, and to handle HTTP GET and
POST requests (request.GET, request.POST)
27
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, ‘polls/index.html’, context)
URLs
Map a user request to the appropriate Django ‘view’
When accessed on the site, regex matching is performed on the path.
If no regex matched, then error handling is done.
Designed to make URLs elegant and understandable
A urls.py file for the base project and an urls.py file for each app.
28
URLs (continued)
<domain_name>/polls/ - directs the request to the views.index function
<domain_name>/polls/4/ - directs the request to the views.detail function with
argument 4
Optional “name” argument to reference a URL
29
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail')
]
Templates
Simply a text file. It can generate any-text based format (HTML, XML, CSV, etc.).
Site-wide templates live in a “templates” directory on the project base
App-specific templates live within the app ‘polls/templates’
Templates encourage separation of application and presentation logic (no Python
knowledge is required for templates)
Django has its own template engine and also supports Jinja2 engine
30
Templates (continued)
Contains variables “{{ }}”, which get replaced when the template is evaluated, and tags
“{% %}” which control the logic of the template
Template inheritance: A base HTML template can be used site-wide, and extended in
each template
31
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{
question.question_text }}</a></li>
{% endfor %}
</ul>
Other components
32
Admin
Useful auto-generated Django admin, which contains generated forms.
Should only be accessible by a trusted staff member to Create, Update, Delete site
content.
33
Admin (continued)
To use the admin, first create a superuser (with username and password):
Once done, login to the admin site at: “<domain_name>/admin/”
Use admin.py files in each app to decide what and how to display model content to the
staff user.
34
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = [‘pub_date’, ‘question_text’]
admin.site.register(Question, QuestionAdmin)
$ python manage.py createsuperuser
Static Files
Includes images, JavaScript and CSS
Create a new directory ‘static’ within your app for these files ‘polls/static’
If using static files outside of an app, set STATICFILES_DIR in the settings file
Use the ‘static’ template tag in templates to avoid hardcoding paths to static files:
35
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
Testing
“Code without tests is broken by design”
- Jacob Kaplan-Moss, one of original Django developers
To run the test cases for an app run:
By default test runner will find any file named “test*.py” in current working directory
To run tests requiring database access subclass “django.test.TestCase”, a subclass of
“unittest.TestCase” from the Python standard library
36
$ python manage.py test polls
Testing (continued)
A very useful Test client which acts as a dummy Web browser can:
● Simulate GET and POST request on a URL
● Check redirects are working
● Test that a given request is rendered by a certain template
37
from django.test import TestCase
class QuestionViewTest(TestCase):
def test_index_view_with_no_questions(self):
"""
If no questions exist, an appropriate message should be displayed
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
Demo
38
[david.gibbons@7V0DZY1 tech_talk]$ tree -I '*.pyc|*~' mysite/
mysite/
|-- db.sqlite3
|-- manage.py
|-- mysite
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| `-- wsgi.py
|-- polls
| |-- admin.py
| |-- __init__.py
| |-- migrations
| | |-- 0001_initial.py
| | `-- __init__.py
| |-- models.py
| |-- static
| | `-- polls
| | |-- images
| | | `-- magic-pony-django-wallpaper.png
| | `-- style.css
| |-- templates
| | `-- polls
| | |-- detail.html
| | |-- index.html
| | `-- results.html
| |-- tests.py
| |-- urls.py
| `-- views.py
`-- templates
`-- admin
`-- base_site.html
39
40
3rd Party Packages
Often prefixed - “django-”:
- djangorestframework
- django-registration-redux
- django-admin-honeypot
- django-debug-toolbar
- django-storages
Many more can be searched for at www.djangopackages.com
41
More topics not touched on, including ...
Internationalisation and Localisation (translation)
Django shell
Caching frameworks
Django deployment
Django Middleware
42
Summary
Started at Lawrence Journal-World newspaper in Kansas, USA
Most downloaded Python web framework, powering many popular websites
in existence today
Architecture is based around models, views, URLs and templates
Other useful “out-of-the-box” components are the admin interface, static file
handling, testing and user management
Excellent documentation - learn by example
43
References and Useful Links
● https://docs.djangoproject.com/en/1.8/
● https://en.wikipedia.org/wiki/Django_(web_framework)
● https://wiki.python.org/moin/WebFrameworks
● http://twoscoopspress.org/
44
Thank you and volunteer for talks!
45

More Related Content

What's hot (20)

PDF
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
IT Event
 
KEY
Introduction to Django
James Casey
 
PDF
Angular js
Eueung Mulyana
 
PDF
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
IMC Institute
 
PDF
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
PPTX
Grails Advanced
Saurabh Dixit
 
TXT
Upload[1]
mirjana stojanova
 
PDF
Vaadin & Web Components
Joonas Lehtinen
 
PDF
Vaadin Components @ Angular U
Joonas Lehtinen
 
PPTX
Working with AngularJS
André Vala
 
PDF
The web - What it has, what it lacks and where it must go - Istanbul
Robert Nyman
 
PDF
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
ODP
JSF 2.0 (JavaEE Webinar)
Roger Kitain
 
PDF
Flash Platformアップデート
Mariko Nishimura
 
PDF
Introduction to React for Frontend Developers
Sergio Nakamura
 
PDF
Using HttpWatch Plug-in with Selenium Automation in Java
Sandeep Tol
 
PDF
Vaadin Components
Joonas Lehtinen
 
PDF
webcomponents (Jfokus 2015)
Hendrik Ebbers
 
PPTX
Selenium Automation in Java Using HttpWatch Plug-in
Sandeep Tol
 
PDF
Web Components for Java Developers
Joonas Lehtinen
 
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
IT Event
 
Introduction to Django
James Casey
 
Angular js
Eueung Mulyana
 
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
IMC Institute
 
Modular Test-driven SPAs with Spring and AngularJS
Gunnar Hillert
 
Grails Advanced
Saurabh Dixit
 
Vaadin & Web Components
Joonas Lehtinen
 
Vaadin Components @ Angular U
Joonas Lehtinen
 
Working with AngularJS
André Vala
 
The web - What it has, what it lacks and where it must go - Istanbul
Robert Nyman
 
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
JSF 2.0 (JavaEE Webinar)
Roger Kitain
 
Flash Platformアップデート
Mariko Nishimura
 
Introduction to React for Frontend Developers
Sergio Nakamura
 
Using HttpWatch Plug-in with Selenium Automation in Java
Sandeep Tol
 
Vaadin Components
Joonas Lehtinen
 
webcomponents (Jfokus 2015)
Hendrik Ebbers
 
Selenium Automation in Java Using HttpWatch Plug-in
Sandeep Tol
 
Web Components for Java Developers
Joonas Lehtinen
 

Similar to An Introduction to Django Web Framework (20)

PDF
A Basic Django Introduction
Ganga Ram
 
PDF
CCCDjango2010.pdf
jayarao21
 
PDF
Intro to Web Development Using Python and Django
Chariza Pladin
 
PPTX
Tango with django
Rajan Kumar Upadhyay
 
PDF
بررسی چارچوب جنگو
railsbootcamp
 
PDF
Introduction to Django
Jagdeep Singh Malhi
 
ODP
Introduction to Django
colinkingswood
 
PDF
Introduction to Django
Joaquim Rocha
 
PDF
Python網站框架絕技: Django 完全攻略班
Paul Chao
 
PDF
Introduction to Python and Django
solutionstreet
 
PDF
django_introduction20141030
Kevin Wu
 
ODP
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Mir Nazim
 
PDF
introduction to Django and its application
mohammedarshadhussai4
 
PPTX
Django course
Nagi Annapureddy
 
PDF
Introduction to django framework
Knoldus Inc.
 
PDF
Rapid web application development using django - Part (1)
Nishant Soni
 
PDF
Django 1.10.3 Getting started
MoniaJ
 
PPTX
Introduction to Django
Ahmed Salama
 
PPTX
Web development with django - Basics Presentation
Shrinath Shenoy
 
PDF
Python & Django TTT
kevinvw
 
A Basic Django Introduction
Ganga Ram
 
CCCDjango2010.pdf
jayarao21
 
Intro to Web Development Using Python and Django
Chariza Pladin
 
Tango with django
Rajan Kumar Upadhyay
 
بررسی چارچوب جنگو
railsbootcamp
 
Introduction to Django
Jagdeep Singh Malhi
 
Introduction to Django
colinkingswood
 
Introduction to Django
Joaquim Rocha
 
Python網站框架絕技: Django 完全攻略班
Paul Chao
 
Introduction to Python and Django
solutionstreet
 
django_introduction20141030
Kevin Wu
 
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Mir Nazim
 
introduction to Django and its application
mohammedarshadhussai4
 
Django course
Nagi Annapureddy
 
Introduction to django framework
Knoldus Inc.
 
Rapid web application development using django - Part (1)
Nishant Soni
 
Django 1.10.3 Getting started
MoniaJ
 
Introduction to Django
Ahmed Salama
 
Web development with django - Basics Presentation
Shrinath Shenoy
 
Python & Django TTT
kevinvw
 
Ad

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Digital Circuits, important subject in CS
contactparinay1
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Ad

An Introduction to Django Web Framework

  • 1. An Introduction to Django Web Framework David Gibbons September 2015
  • 2. Joined Ammeon almost 2 years ago in Porcos team Previously worked with Django web framework.... and liked it. Fast development of new features, clean architecture, on top of a fast, stable, secure framework. Developed a Django-powered Web Application for energy management Over 100 users logged in each week to view, analyse their data Easy to manage user permissions for specific website features About Me 2
  • 5. 5
  • 6. 6 History Created at Lawrence Journal-World newspaper in 2003 in Kansas, USA Adrian Holovaty and Simon Willison initially wrote from scratch as nothing fitted Historically excellent documentation Named after French Guitarist Django Reinhardt Open sourced in 2005
  • 7. A high-level Python Web framework that encourages rapid development and clean, pragmatic design A free and open source web framework (public repository at https://github. com/django/django) Model–View–Controller (MVC) architectural pattern Don’t Repeat Yourself (DRY) principle Lots of out-of-the box features What is Django? 7
  • 9. What is a Web Framework? 9 Software framework designed to simplify your web development life Handles many of the common operations associated with web development including: ● accessing the database ● creating HTML templates ● managing sessions Promotes code reuse
  • 10. Some other popular Python Web Frameworks 10 Flask: micro framework that provides a simple template for web development Tornado: web framework and asynchronous networking library, noted for high performance Bottle: fast, simple lightweight micro web-framework Pyramid: MVC framework with flexible component choices CherryPy: mature object-oriented web framework - compact and simple
  • 11. 11 How popular is Django? PyPI is the official 3rd party package repository for Python Stats available on number of downloads in last week, month, year. Django is the most downloaded web framework, is regularly updated by community
  • 13. Django and LITP Plugin development similar to developing Django apps: - Defined directory structure - Makes use of classes and functions provided by a “core” - Form validation in Django is similar to LITP plugin validation - Models and migrations in Django similar to LITP APIs and migrations 13
  • 15. Build a web application to allow the public to vote in polls, and view results Typical requirement for a online news website (such a Lawrence Journal-World) Three interested parties: ● A software developer creates the necessary models ● A site administrator creates/updates/deletes the polls ● A public website visitor votes in the polls and views results Same example application as the official Django tutorial, for more detailed explanation see https://docs.djangoproject.com/en/1.8/intro/tutorial01/ Polls Web Application 15
  • 16. 1. Django 1.8 needs at least Python 2.7 installed! 2. Create a new project directory, install Django (preferable with pip and virtualenv) 3. To create Django project “mysite” run: Creates a directory structure which is the base of project: 16 mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py $ django-admin.py startproject mysite Django Quick Start Guide
  • 17. 4. Django supports 4 databases: Update the settings.py file to use sqlite and ‘Europe/Dublin’. 5. To create the sqlite file and database tables initially needed by Django run: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } TIME_ZONE = 'Europe/Dublin' 17 $ python manage.py migrate
  • 18. 6. Run the built-in Django development server (default port 8000): 7. Open 127.0.0.1:8000 in web browser, and you should see a page saying “It worked!” 18 $ python manage.py runserver
  • 19. 8. A Django “project” is a collection of Django “app”s. An app is an application that does something specific (blog or poll) To start our new polls app, cd into ‘mysite’ and run: This creates the directory structure for your ‘polls’ app: 19 $ django-admin.py startapp polls polls/ __init__.py admin.py migrations/ __init__.py models.py tests.py views.py Application Quick Start Guide
  • 20. 9. Add polls application to INSTALLED_APPS in settings.py to activate ‘polls’ models 10. Start working on the models, views, urls and templates for the polls app! 20 INSTALLED_APPS = ( ... ‘polls’ )
  • 22. What is MVC (Model-View-Controller)? Software architectural pattern for user interfaces, popular in web applications. Other MVC frameworks: Ruby-on-rails (Ruby), ASP.NET MVC (C# or Visual Basic) Alternative Django-specific acronym is MTV (Model, Template, View) 22
  • 23. Template - User facing URLs - URL Configuration View - Business Logic Model - Database Table 23
  • 24. Models Single definitive source of information about data Define the interface to the database, an auto-generated database API Generally maps to a single database table, and each attribute represents a database field from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') 24
  • 25. Once the models are defined, two commands are run to create the database tables: Models (continued) 25 $ python manage.py makemigrations polls $ python manage.py migrate polls
  • 26. Views Python function which takes a Web request, and returns a Web response This response can be HTML for a web page, a redirect, a 404 Not Found error etc. Contains the logic on what is returned from a particular request Function-based or class-based 26 from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ‘. ’.join([q.question_text for q in latest_question_list]) return HttpResponse(output)
  • 27. Views (continued) Often required to return some variables from the model to a HTML template. The useful ‘render’ shortcut: Views are also used to check that a user is logged in, and to handle HTTP GET and POST requests (request.GET, request.POST) 27 from django.shortcuts import render from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, ‘polls/index.html’, context)
  • 28. URLs Map a user request to the appropriate Django ‘view’ When accessed on the site, regex matching is performed on the path. If no regex matched, then error handling is done. Designed to make URLs elegant and understandable A urls.py file for the base project and an urls.py file for each app. 28
  • 29. URLs (continued) <domain_name>/polls/ - directs the request to the views.index function <domain_name>/polls/4/ - directs the request to the views.detail function with argument 4 Optional “name” argument to reference a URL 29 from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail') ]
  • 30. Templates Simply a text file. It can generate any-text based format (HTML, XML, CSV, etc.). Site-wide templates live in a “templates” directory on the project base App-specific templates live within the app ‘polls/templates’ Templates encourage separation of application and presentation logic (no Python knowledge is required for templates) Django has its own template engine and also supports Jinja2 engine 30
  • 31. Templates (continued) Contains variables “{{ }}”, which get replaced when the template is evaluated, and tags “{% %}” which control the logic of the template Template inheritance: A base HTML template can be used site-wide, and extended in each template 31 <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul>
  • 33. Admin Useful auto-generated Django admin, which contains generated forms. Should only be accessible by a trusted staff member to Create, Update, Delete site content. 33
  • 34. Admin (continued) To use the admin, first create a superuser (with username and password): Once done, login to the admin site at: “<domain_name>/admin/” Use admin.py files in each app to decide what and how to display model content to the staff user. 34 from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): fields = [‘pub_date’, ‘question_text’] admin.site.register(Question, QuestionAdmin) $ python manage.py createsuperuser
  • 35. Static Files Includes images, JavaScript and CSS Create a new directory ‘static’ within your app for these files ‘polls/static’ If using static files outside of an app, set STATICFILES_DIR in the settings file Use the ‘static’ template tag in templates to avoid hardcoding paths to static files: 35 {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
  • 36. Testing “Code without tests is broken by design” - Jacob Kaplan-Moss, one of original Django developers To run the test cases for an app run: By default test runner will find any file named “test*.py” in current working directory To run tests requiring database access subclass “django.test.TestCase”, a subclass of “unittest.TestCase” from the Python standard library 36 $ python manage.py test polls
  • 37. Testing (continued) A very useful Test client which acts as a dummy Web browser can: ● Simulate GET and POST request on a URL ● Check redirects are working ● Test that a given request is rendered by a certain template 37 from django.test import TestCase class QuestionViewTest(TestCase): def test_index_view_with_no_questions(self): """ If no questions exist, an appropriate message should be displayed """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.")
  • 39. [david.gibbons@7V0DZY1 tech_talk]$ tree -I '*.pyc|*~' mysite/ mysite/ |-- db.sqlite3 |-- manage.py |-- mysite | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- polls | |-- admin.py | |-- __init__.py | |-- migrations | | |-- 0001_initial.py | | `-- __init__.py | |-- models.py | |-- static | | `-- polls | | |-- images | | | `-- magic-pony-django-wallpaper.png | | `-- style.css | |-- templates | | `-- polls | | |-- detail.html | | |-- index.html | | `-- results.html | |-- tests.py | |-- urls.py | `-- views.py `-- templates `-- admin `-- base_site.html 39
  • 40. 40
  • 41. 3rd Party Packages Often prefixed - “django-”: - djangorestframework - django-registration-redux - django-admin-honeypot - django-debug-toolbar - django-storages Many more can be searched for at www.djangopackages.com 41
  • 42. More topics not touched on, including ... Internationalisation and Localisation (translation) Django shell Caching frameworks Django deployment Django Middleware 42
  • 43. Summary Started at Lawrence Journal-World newspaper in Kansas, USA Most downloaded Python web framework, powering many popular websites in existence today Architecture is based around models, views, URLs and templates Other useful “out-of-the-box” components are the admin interface, static file handling, testing and user management Excellent documentation - learn by example 43
  • 44. References and Useful Links ● https://docs.djangoproject.com/en/1.8/ ● https://en.wikipedia.org/wiki/Django_(web_framework) ● https://wiki.python.org/moin/WebFrameworks ● http://twoscoopspress.org/ 44
  • 45. Thank you and volunteer for talks! 45