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)

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

Similar to An Introduction to Django Web Framework (20)

بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
railsbootcamp
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
Nishant Soni
 
Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docx
fantabulous2024
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
Felipe Queiroz
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Django Framework Interview Question and Answer partOne.pptx
Django Framework Interview Question and Answer partOne.pptxDjango Framework Interview Question and Answer partOne.pptx
Django Framework Interview Question and Answer partOne.pptx
Md. Naimur Rahman
 
Django
DjangoDjango
Django
sisibeibei
 
Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
Morteza Zohoori Shoar
 
Django by rj
Django by rjDjango by rj
Django by rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
Akash Rajguru
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
 
Django framework
Django framework Django framework
Django framework
TIB Academy
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
Django introduction
Django introductionDjango introduction
Django introduction
Joaquim Rocha
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
 
Django
DjangoDjango
Django
Harmeet Lamba
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
Haiqi Chen
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
railsbootcamp
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
Nishant Soni
 
Company Visitor Management System Report.docx
Company Visitor Management System Report.docxCompany Visitor Management System Report.docx
Company Visitor Management System Report.docx
fantabulous2024
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Django Framework Interview Question and Answer partOne.pptx
Django Framework Interview Question and Answer partOne.pptxDjango Framework Interview Question and Answer partOne.pptx
Django Framework Interview Question and Answer partOne.pptx
Md. Naimur Rahman
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
Akash Rajguru
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
 
Django framework
Django framework Django framework
Django framework
TIB Academy
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
Haiqi Chen
 
Ad

Recently uploaded (20)

AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
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