Rajan K Upadhyay 
1
Programming Languages 
Popular 
Programming Languages > 500 
Frameworks > 90000 
at least what Wikipedia says 
What Really I should Learn ? 
2
Lets go back & check last software you developed 
• Without Alternatives, how difficult it was to estimate ? 
• Ideas -> Conceptualization -> Enterprise Ready was full of Effort, Pain, 
Time waste, Complexity & Change !!! 
• Was my system adaptive to the change that business demand? … God 
it was really nightmare to maintain the code …. 
• What is the time it took to get the customer from a frustrated to a happy 
customer ? also the time it took to develop version 2, with different 
requirements & scale: 
3
Time is an essence 
Python : Django A complete framework 
A Web Framework that shortens the Time it takes to develop 
software in at least an Order of Magnitude. while also 
tremendously minimizing Effort Pain, Time waste, Complexity, 
Cost of change & more 
9/1/2014 4
Python: Language of Best 
• By The organizations attracting the best Programmers 
in the world 
Google, NASA, MIT 
5
• “The framework for perfectionists 
with deadlines” 
• Model-Template-View ( MTV ) not as 
complex as MVC 
• Flexible template language that can 
be used to generate HTML, CSV, 
Email or any other format 
• Includes ORM that supports many 
databases – Postgresql, MySQL, 
Oracle, SQLite 
• Lots of extras included – 
middleware, csrf protections, 
sessions, caching, authentication 
• Written in C – high 
performance, ability to link to 
C libraries for extensions 
• Interpreted script language 
compiled on the fly into byte 
code 
• Easier to read coding 
standards – whitespace 
sensitive 
• Object Oriented 
WHY 
6
Scalability 
• Django runs on regular web servers, such as 
Apache, Lighty or Nginx, using a built-in Python 
or WSGI adapter 
• This makes it very lightweight & scalable, as any 
LAMP deployment 
o There are examples of sites that handle MM reqs/hour, using less 
than 10 servers 
7
IT Acceptance 
• IT environments today are mostly familiar with 
Java 
• Solution: use Jython that compiles Python to 
bytecode 
o Package a Django project as .war 
o Sun constantly improves Jython & maintains compatibility /w 
Django 
8
DJANGO: 
QUICK OVERVIEW 
9
Project File Structure 
django-admin.py startproject 
<PROJECT_ROOT> 
manage.py 
<PROJECT_DIR> 
__init__.py 
settings.py 
urls.py 
wsgi.py 
10
settings.py 
• Defines settings used by a Django application 
• Referenced by wsgi.py to bootstrap the project 
loading 
• Techniques for managing dev vs prod settings: 
o Create settings-dev.py and settings-prod.py and use symlink to link 
settings.py to the correct settings 
o Factor out common settings into base-settings.py and import. Use 
conditionals to load correct settings based on DEBUG or other setting 
11
Sample Settings… 
DEBUG = True 
TEMPLATE_DEBUG = True 
ALLOWED_HOSTS = [] 
# Application definition 
INSTALLED_APPS = ( 
'django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
) 
12
Django Apps 
• Reusable modules 
• django-admin.py startapp <app_name> 
• Creates stub layout: 
<APP_ROOT> 
admin.py 
models.py 
templates (directory) 
tests.py 
views.py 
urls.py 
13
Django Models 
• Defined in models.py 
• Typically inherit from django.db.models.Model 
Example Model: 
from django.db import models 
class TestModel(models.Model): 
name = models.CharField(max_length = 20) 
age = models.IntegerField() 
14
Models (cont’d) 
• Default is to set NOT NULL on all fields. Override by 
adding null = True to field definition: 
name = models.CharField(max_length=20, null = 
True) 
• Relationships defined through special field types: 
models.OneToOneField(model) 
models.ForeignKey(model) 
models.ManyToManyField(model) 
15
Models (cont’) 
• Need Nulls in a Boolean Field? Use 
models.NullBooleanField() 
• Set Default value with “default”: 
count = models.IntegerField(default = 0) 
• Use a inner Meta class to define additional options, 
especially useful for abstract classes: 
class TestModel(models.Model): 
class Meta: 
abstract = True 
16
Model Methods 
• model.save(self, *args, **kwargs) 
• model.delete(self, *args, **kwargs) 
• model.get_absolute_url(self) 
• model.__str__(self) [Python 3] 
model.__unicode__(self) [Python 2] 
• Override with super(MODEL, self).save(*args, 
**kwargs) 
17
Activating a Model 
• Add the app to INSTALLED_APPS in settings.py 
• Run manage.py validate 
• Run manage.py syncdb 
• Migrations 
o Write custom script or manually handle migrations 
o Use South 
18
Selecting Objects 
• Models include a default manager called objects 
• Manager methods allow selecting all or some 
instances 
Question.objects.all() 
Question.objects.get(pk = 1) 
Use try block, throws DoesNotExist 
exception if no match 
Question.objects.filter(created_date__lt = ‘2014- 
01-01’) 
• Returns QuerySet 
19
Introspecting Legacy 
Models 
• manage.py inspectdb 
• Cut and paste generated code into models.py – 
Easy!! 
20
Full Sample 
from django.db import models 
from datetime import datetime 
class TimestampedModel(models.Model): 
created_datetime = models.DateTimeField() 
updated_datetime = models.DateTimeField() 
def save(self, *args, **kwargs): 
if self.id is None: 
self.created_datetime = datetime.now() 
updated_datetime = datetime.now() 
super(TimestampedModel,self).save(*args, **kwargs) 
class Meta: 
abstract = True 
21
Full Sample (cont’d) 
class Question(TimestampedModel): 
question_text = models.CharField(max_length = 200) 
def __str__(self): 
return self.question_text 
22
Function vs. Class Views 
• Django allows two styles of views – functions or class 
based views 
• Functions – take a request object as the first 
parameter and must return a response object 
• Class based views – allow CRUD operations with 
minimal code. Can inherit from multiple generic 
view classes (i.e. Mixins) 
23
Sample – Viewing a List 
of Questions 
• Function based: 
from .models import Question 
from django.shortcuts import render_to_response 
def question_list(request): 
questions = Question.objects.all() 
return render_to_response(‘question_list.html’, { 
‘questions’:questions}) 
24
Quick CRUD Operations 
with Generic Views 
• ListView 
• UpdateView 
• CreateView 
• If Model is specified, automagically creates a 
matching ModelForm 
• Form will save the Model if data passes validation 
• Override form_valid() method to provide custom 
logic (i.e sending email or setting additional fields) 
25
Sample – As Class Based 
View 
from .models import Question 
from django.views.generic import ListView 
class QuestionList(ListView): 
model = Question 
context_object_name = ‘questions’ 
26
Django Templates 
• Very simple syntax: 
variables = {{variable_name}} 
template tags = {%tag%} 
• Flexible – can be used to render html, text, csv, 
email, you name it! 
• Dot notation – template engine attempts to resolve 
by looking for matching attributes, hashes and 
methods 
27
Question List Template 
<!doctype html> 
<html lang=en> 
<head> 
<meta charset=utf-8> 
<title>List of Questions</title> 
</head> 
<body> 
{%if questions%} 
<ul> 
{%for q in questions%} 
<li>{{q.question_text}}</li> 
{%endfor%} 
</ul> 
{%else%} 
<p>No questions have been defined</p> 
{%endif%} 
</body> 
</html> 
28
urls.py 
• Defines routes to send urls to various views 
• Can use regular expressions 
• Extract parameters from a url and pass to the view 
as a named parameter: 
r(‘^question/(?P<question_id>d+)/$’,’views.question_ 
detail’) 
• Extensible – urls.py can include additional url files 
from apps: 
r(‘^question/’,include(question.urls)) 
29
Forms in Django 
• django.forms provides a class to build HTML forms 
and validation. Example: 
from django import forms 
class EditQuestionForm(forms.Form): 
question_text = forms.CharField(max_length = 200) 
• Often redundant when creating forms that work on 
a single model 
30
ModelForms 
• Automatically generate a form from a model. 
• Handles saving a bound model 
• Can specify fields to be included or excluded in the 
form 
• Sample: 
from django.forms import ModelForm 
from .models import Question 
class QuestionForm(ModelForm): 
class Meta: 
model = Question 
fields = [‘question_text’] 
31
Using a ModelForm 
• Create an instance of an empty form: 
form = QuestionForm() 
• Create a form to update an existing instance of a 
model: 
question = Question.objects.get(pk = 1) 
form = QuestionForm(instance = question) 
• Pass the form into the template and use the form 
methods to render the form: 
form.as_p 
form.as_ul 
form.<field_name> 
form.<field_name>.errors 
32
Request & Response 
• Request object encapsulate the request and provide 
access to a number of attributes and methods for 
accessing cookies, sessions, the logged in user object, 
meta data (i.e environment variables), 
• Response objects are returned to the browser. Can set 
content type, content length, response does not have 
to return HTML or a rendered template 
• Special response types allow for common functionality: 
HttpResponeRedirect 
Http404 
HttpStreamingResponse 
33
Django Extras 
• CRSF Middleware – enabled by default. Include 
template tag in all forms: 
{%csrf_token%} 
• Authentication 
• Caching 
• Sessions 
• Messages 
• Email 
• Logging 
34
Auth Decorators 
• Live in django.contrib.auth.decorators 
• login_required 
@login_required 
def function_view(request): 
…. 
• user_passes_test (can be used with lambda 
functions for real power) – 
@user_passes_test(lambda u: u.is_staff) 
def function_view(request): 
… 
• has_perms – test for user permissions 
35
Demo: 30 mins 
Let’s develop an Release Tracking system 
o Create Business Data Model 
o Database CRUD Operations to manage/add/edit/delete Releases 
o Rich Web UI (search, filters, last actions) 
o Users management (permissions, groups), User logging, Access level 
control 
o Scalable deployment (any # of users) 
36
Step1: Settings: Connect to 
Database 
• DATABASES = { 
• 'default': { 
• 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 
• 'NAME': ‘release', # Or path to database file if using sqlite3. 
• # The following settings are not used with sqlite3: 
• 'USER': 'root', 
• 'PASSWORD': ‘', 
• 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 
• 'PORT': '', # Set to empty string for default. 
• } 
• } 
37
Step2: Data Model 
from django.db import models 
class Environment(models.Model): 
environment = models.CharField(null=False, max_length=200) 
# Create your models here. 
class Release(models.Model): 
dateCreated = models.DateField(null=False, auto_now_add=True) 
releaseDate = models.DateField(null=False) 
releaseTitle = models.CharField(null=False, max_length=200) 
releaseEnv = models.ForeignKey(Environment) 
38
Step3: Sync DB 
django_manage.py syncdb 
Whoooo ---- Your DB tables are created 
What Next  Lets create some Interfaces 
39
Register Admin 
from django.db import models 
from django.contrib import admin 
class Environment(models.Model): 
environment = models.CharField(null=False, max_length=200) 
# Create your models here. 
class Release(models.Model): 
dateCreated = models.DateField(null=False, auto_now_add=True) 
releaseDate = models.DateField(null=False) 
releaseTitle = models.CharField(null=False, max_length=200) 
releaseEnv = models.ForeignKey(Environment) 
admin.site.register(Release) 
admin.site.register(Environment) 
40
Admin Interface Ready 
• Run  manage.py runserver 8000 
http://127.0.0.1:8000/admin/ 
- Entire CRUD Operation for 
Models 
- User Authentication, Groups, 
Access Level & control 
- User Log 
- Multisite & Multi Application 
41
Views: Front End 
• Setup a URL pattern : Edit url.py 
url(r'^$', 'ReleaseTracker.views.home', name='home'), 
. Create view as home 
# Create your views here. 
from django.http import HttpResponse 
from rtracker.models import Environment 
from rtracker.models import Release 
from django.shortcuts import get_object_or_404, render_to_response 
from django.template import RequestContext 
def home(request): 
releaseitems = Release.objects.all() 
return render_to_response('home.html', {'releaseitems': releaseitems}, 
context_instance=RequestContext(request)) 
42
Create Template 
Create home.html in templates 
<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
</head> 
<body> 
{# you can include templates #} 
{% include "nav.html" %} 
{% for release in releaseitems %} 
{{release.releaseTitle}} 
{% endfor %} 
</body> 
</html> 
43
FRONT END 
• Open http://127.0.0.1:8000/ 
You will be able to see the model data 
44

More Related Content

PDF
The Django Book - Chapter 5: Models
KEY
Making Django and NoSQL Play Nice
PDF
Django Introduction & Tutorial
PDF
Django Overview
ODP
Introduction to Django
PDF
Django best practices for logging and signals
PDF
Working with the django admin
KEY
Geotalk presentation
The Django Book - Chapter 5: Models
Making Django and NoSQL Play Nice
Django Introduction & Tutorial
Django Overview
Introduction to Django
Django best practices for logging and signals
Working with the django admin
Geotalk presentation

What's hot (20)

PPTX
Why Django for Web Development
PDF
Django Mongodb Engine
PPT
Django and Mongoengine
PPT
Django
PPTX
The Django Web Application Framework 2
PDF
Django a whirlwind tour
PPTX
PDF
Backbone.js
PPTX
Javascript first-class citizenery
PDF
Django Heresies
PDF
Create responsive websites with Django, REST and AngularJS
PDF
Understanding backbonejs
PDF
In-depth changes to Drupal 8 javascript
PDF
Django for mobile applications
PDF
Intro To Mvc Development In Php
PPTX
AngularJS Architecture
PDF
Building Pluggable Web Applications using Django
PDF
Mini Curso de Django
PDF
Viking academy backbone.js
PDF
Kiss PageObjects [01-2017]
Why Django for Web Development
Django Mongodb Engine
Django and Mongoengine
Django
The Django Web Application Framework 2
Django a whirlwind tour
Backbone.js
Javascript first-class citizenery
Django Heresies
Create responsive websites with Django, REST and AngularJS
Understanding backbonejs
In-depth changes to Drupal 8 javascript
Django for mobile applications
Intro To Mvc Development In Php
AngularJS Architecture
Building Pluggable Web Applications using Django
Mini Curso de Django
Viking academy backbone.js
Kiss PageObjects [01-2017]
Ad

Similar to Tango with django (20)

PDF
django_introduction20141030
PDF
GDG Addis - An Introduction to Django and App Engine
KEY
Introduction Django
PDF
Introduction to Django
PPTX
Web development with django - Basics Presentation
PDF
A Basic Django Introduction
PDF
Django interview Questions| Edureka
PPTX
templates in Django material : Training available at Baabtra
PDF
بررسی چارچوب جنگو
PDF
Introduction to Django
PDF
Agile_goa_2013_clean_code_tdd
PDF
EKON 23 Code_review_checklist
PPTX
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
PPTX
Discovering Django - zekeLabs
PDF
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
PDF
Django Documentation
PDF
A gentle intro to the Django Framework
PDF
Introduction to AngularJS
PDF
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
KEY
國民雲端架構 Django + GAE
django_introduction20141030
GDG Addis - An Introduction to Django and App Engine
Introduction Django
Introduction to Django
Web development with django - Basics Presentation
A Basic Django Introduction
Django interview Questions| Edureka
templates in Django material : Training available at Baabtra
بررسی چارچوب جنگو
Introduction to Django
Agile_goa_2013_clean_code_tdd
EKON 23 Code_review_checklist
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Discovering Django - zekeLabs
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
Django Documentation
A gentle intro to the Django Framework
Introduction to AngularJS
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
國民雲端架構 Django + GAE
Ad

More from Rajan Kumar Upadhyay (8)

PDF
Speed Up RPA Deployment 10 times faster
PPTX
RPA & Supply Chain
DOCX
Features of globalization and india in global economy
DOCX
State of Retail E-commerce In India
PPTX
Hadoop & distributed cloud computing
PPT
Nextop Cloud computing Platform
PPTX
Data analysis & decisions
PDF
Business Intelligence & its Best Practices
Speed Up RPA Deployment 10 times faster
RPA & Supply Chain
Features of globalization and india in global economy
State of Retail E-commerce In India
Hadoop & distributed cloud computing
Nextop Cloud computing Platform
Data analysis & decisions
Business Intelligence & its Best Practices

Recently uploaded (20)

PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PPTX
Blending method and technology for hydrogen.pptx
PPTX
Information-Technology-in-Human-Society.pptx
PDF
EIS-Webinar-Regulated-Industries-2025-08.pdf
PDF
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
PDF
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
PPTX
Information-Technology-in-Human-Society (2).pptx
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
Ebook - The Future of AI A Comprehensive Guide.pdf
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PDF
Chapter 1: computer maintenance and troubleshooting
PPTX
How to use fields_get method in Odoo 18
PDF
The AI Revolution in Customer Service - 2025
PDF
Altius execution marketplace concept.pdf
PDF
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
PPTX
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
PDF
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
PPTX
From XAI to XEE through Influence and Provenance.Controlling model fairness o...
PDF
Streamline Vulnerability Management From Minimal Images to SBOMs
PPTX
Build automations faster and more reliably with UiPath ScreenPlay
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
Blending method and technology for hydrogen.pptx
Information-Technology-in-Human-Society.pptx
EIS-Webinar-Regulated-Industries-2025-08.pdf
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
Slides World Game (s) Great Redesign Eco Economic Epochs.pdf
Information-Technology-in-Human-Society (2).pptx
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
Ebook - The Future of AI A Comprehensive Guide.pdf
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Chapter 1: computer maintenance and troubleshooting
How to use fields_get method in Odoo 18
The AI Revolution in Customer Service - 2025
Altius execution marketplace concept.pdf
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
From XAI to XEE through Influence and Provenance.Controlling model fairness o...
Streamline Vulnerability Management From Minimal Images to SBOMs
Build automations faster and more reliably with UiPath ScreenPlay

Tango with django

  • 2. Programming Languages Popular Programming Languages > 500 Frameworks > 90000 at least what Wikipedia says What Really I should Learn ? 2
  • 3. Lets go back & check last software you developed • Without Alternatives, how difficult it was to estimate ? • Ideas -> Conceptualization -> Enterprise Ready was full of Effort, Pain, Time waste, Complexity & Change !!! • Was my system adaptive to the change that business demand? … God it was really nightmare to maintain the code …. • What is the time it took to get the customer from a frustrated to a happy customer ? also the time it took to develop version 2, with different requirements & scale: 3
  • 4. Time is an essence Python : Django A complete framework A Web Framework that shortens the Time it takes to develop software in at least an Order of Magnitude. while also tremendously minimizing Effort Pain, Time waste, Complexity, Cost of change & more 9/1/2014 4
  • 5. Python: Language of Best • By The organizations attracting the best Programmers in the world Google, NASA, MIT 5
  • 6. • “The framework for perfectionists with deadlines” • Model-Template-View ( MTV ) not as complex as MVC • Flexible template language that can be used to generate HTML, CSV, Email or any other format • Includes ORM that supports many databases – Postgresql, MySQL, Oracle, SQLite • Lots of extras included – middleware, csrf protections, sessions, caching, authentication • Written in C – high performance, ability to link to C libraries for extensions • Interpreted script language compiled on the fly into byte code • Easier to read coding standards – whitespace sensitive • Object Oriented WHY 6
  • 7. Scalability • Django runs on regular web servers, such as Apache, Lighty or Nginx, using a built-in Python or WSGI adapter • This makes it very lightweight & scalable, as any LAMP deployment o There are examples of sites that handle MM reqs/hour, using less than 10 servers 7
  • 8. IT Acceptance • IT environments today are mostly familiar with Java • Solution: use Jython that compiles Python to bytecode o Package a Django project as .war o Sun constantly improves Jython & maintains compatibility /w Django 8
  • 10. Project File Structure django-admin.py startproject <PROJECT_ROOT> manage.py <PROJECT_DIR> __init__.py settings.py urls.py wsgi.py 10
  • 11. settings.py • Defines settings used by a Django application • Referenced by wsgi.py to bootstrap the project loading • Techniques for managing dev vs prod settings: o Create settings-dev.py and settings-prod.py and use symlink to link settings.py to the correct settings o Factor out common settings into base-settings.py and import. Use conditionals to load correct settings based on DEBUG or other setting 11
  • 12. Sample Settings… DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) 12
  • 13. Django Apps • Reusable modules • django-admin.py startapp <app_name> • Creates stub layout: <APP_ROOT> admin.py models.py templates (directory) tests.py views.py urls.py 13
  • 14. Django Models • Defined in models.py • Typically inherit from django.db.models.Model Example Model: from django.db import models class TestModel(models.Model): name = models.CharField(max_length = 20) age = models.IntegerField() 14
  • 15. Models (cont’d) • Default is to set NOT NULL on all fields. Override by adding null = True to field definition: name = models.CharField(max_length=20, null = True) • Relationships defined through special field types: models.OneToOneField(model) models.ForeignKey(model) models.ManyToManyField(model) 15
  • 16. Models (cont’) • Need Nulls in a Boolean Field? Use models.NullBooleanField() • Set Default value with “default”: count = models.IntegerField(default = 0) • Use a inner Meta class to define additional options, especially useful for abstract classes: class TestModel(models.Model): class Meta: abstract = True 16
  • 17. Model Methods • model.save(self, *args, **kwargs) • model.delete(self, *args, **kwargs) • model.get_absolute_url(self) • model.__str__(self) [Python 3] model.__unicode__(self) [Python 2] • Override with super(MODEL, self).save(*args, **kwargs) 17
  • 18. Activating a Model • Add the app to INSTALLED_APPS in settings.py • Run manage.py validate • Run manage.py syncdb • Migrations o Write custom script or manually handle migrations o Use South 18
  • 19. Selecting Objects • Models include a default manager called objects • Manager methods allow selecting all or some instances Question.objects.all() Question.objects.get(pk = 1) Use try block, throws DoesNotExist exception if no match Question.objects.filter(created_date__lt = ‘2014- 01-01’) • Returns QuerySet 19
  • 20. Introspecting Legacy Models • manage.py inspectdb • Cut and paste generated code into models.py – Easy!! 20
  • 21. Full Sample from django.db import models from datetime import datetime class TimestampedModel(models.Model): created_datetime = models.DateTimeField() updated_datetime = models.DateTimeField() def save(self, *args, **kwargs): if self.id is None: self.created_datetime = datetime.now() updated_datetime = datetime.now() super(TimestampedModel,self).save(*args, **kwargs) class Meta: abstract = True 21
  • 22. Full Sample (cont’d) class Question(TimestampedModel): question_text = models.CharField(max_length = 200) def __str__(self): return self.question_text 22
  • 23. Function vs. Class Views • Django allows two styles of views – functions or class based views • Functions – take a request object as the first parameter and must return a response object • Class based views – allow CRUD operations with minimal code. Can inherit from multiple generic view classes (i.e. Mixins) 23
  • 24. Sample – Viewing a List of Questions • Function based: from .models import Question from django.shortcuts import render_to_response def question_list(request): questions = Question.objects.all() return render_to_response(‘question_list.html’, { ‘questions’:questions}) 24
  • 25. Quick CRUD Operations with Generic Views • ListView • UpdateView • CreateView • If Model is specified, automagically creates a matching ModelForm • Form will save the Model if data passes validation • Override form_valid() method to provide custom logic (i.e sending email or setting additional fields) 25
  • 26. Sample – As Class Based View from .models import Question from django.views.generic import ListView class QuestionList(ListView): model = Question context_object_name = ‘questions’ 26
  • 27. Django Templates • Very simple syntax: variables = {{variable_name}} template tags = {%tag%} • Flexible – can be used to render html, text, csv, email, you name it! • Dot notation – template engine attempts to resolve by looking for matching attributes, hashes and methods 27
  • 28. Question List Template <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>List of Questions</title> </head> <body> {%if questions%} <ul> {%for q in questions%} <li>{{q.question_text}}</li> {%endfor%} </ul> {%else%} <p>No questions have been defined</p> {%endif%} </body> </html> 28
  • 29. urls.py • Defines routes to send urls to various views • Can use regular expressions • Extract parameters from a url and pass to the view as a named parameter: r(‘^question/(?P<question_id>d+)/$’,’views.question_ detail’) • Extensible – urls.py can include additional url files from apps: r(‘^question/’,include(question.urls)) 29
  • 30. Forms in Django • django.forms provides a class to build HTML forms and validation. Example: from django import forms class EditQuestionForm(forms.Form): question_text = forms.CharField(max_length = 200) • Often redundant when creating forms that work on a single model 30
  • 31. ModelForms • Automatically generate a form from a model. • Handles saving a bound model • Can specify fields to be included or excluded in the form • Sample: from django.forms import ModelForm from .models import Question class QuestionForm(ModelForm): class Meta: model = Question fields = [‘question_text’] 31
  • 32. Using a ModelForm • Create an instance of an empty form: form = QuestionForm() • Create a form to update an existing instance of a model: question = Question.objects.get(pk = 1) form = QuestionForm(instance = question) • Pass the form into the template and use the form methods to render the form: form.as_p form.as_ul form.<field_name> form.<field_name>.errors 32
  • 33. Request & Response • Request object encapsulate the request and provide access to a number of attributes and methods for accessing cookies, sessions, the logged in user object, meta data (i.e environment variables), • Response objects are returned to the browser. Can set content type, content length, response does not have to return HTML or a rendered template • Special response types allow for common functionality: HttpResponeRedirect Http404 HttpStreamingResponse 33
  • 34. Django Extras • CRSF Middleware – enabled by default. Include template tag in all forms: {%csrf_token%} • Authentication • Caching • Sessions • Messages • Email • Logging 34
  • 35. Auth Decorators • Live in django.contrib.auth.decorators • login_required @login_required def function_view(request): …. • user_passes_test (can be used with lambda functions for real power) – @user_passes_test(lambda u: u.is_staff) def function_view(request): … • has_perms – test for user permissions 35
  • 36. Demo: 30 mins Let’s develop an Release Tracking system o Create Business Data Model o Database CRUD Operations to manage/add/edit/delete Releases o Rich Web UI (search, filters, last actions) o Users management (permissions, groups), User logging, Access level control o Scalable deployment (any # of users) 36
  • 37. Step1: Settings: Connect to Database • DATABASES = { • 'default': { • 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. • 'NAME': ‘release', # Or path to database file if using sqlite3. • # The following settings are not used with sqlite3: • 'USER': 'root', • 'PASSWORD': ‘', • 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. • 'PORT': '', # Set to empty string for default. • } • } 37
  • 38. Step2: Data Model from django.db import models class Environment(models.Model): environment = models.CharField(null=False, max_length=200) # Create your models here. class Release(models.Model): dateCreated = models.DateField(null=False, auto_now_add=True) releaseDate = models.DateField(null=False) releaseTitle = models.CharField(null=False, max_length=200) releaseEnv = models.ForeignKey(Environment) 38
  • 39. Step3: Sync DB django_manage.py syncdb Whoooo ---- Your DB tables are created What Next  Lets create some Interfaces 39
  • 40. Register Admin from django.db import models from django.contrib import admin class Environment(models.Model): environment = models.CharField(null=False, max_length=200) # Create your models here. class Release(models.Model): dateCreated = models.DateField(null=False, auto_now_add=True) releaseDate = models.DateField(null=False) releaseTitle = models.CharField(null=False, max_length=200) releaseEnv = models.ForeignKey(Environment) admin.site.register(Release) admin.site.register(Environment) 40
  • 41. Admin Interface Ready • Run  manage.py runserver 8000 http://127.0.0.1:8000/admin/ - Entire CRUD Operation for Models - User Authentication, Groups, Access Level & control - User Log - Multisite & Multi Application 41
  • 42. Views: Front End • Setup a URL pattern : Edit url.py url(r'^$', 'ReleaseTracker.views.home', name='home'), . Create view as home # Create your views here. from django.http import HttpResponse from rtracker.models import Environment from rtracker.models import Release from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext def home(request): releaseitems = Release.objects.all() return render_to_response('home.html', {'releaseitems': releaseitems}, context_instance=RequestContext(request)) 42
  • 43. Create Template Create home.html in templates <!DOCTYPE html> <html> <head> <title></title> </head> <body> {# you can include templates #} {% include "nav.html" %} {% for release in releaseitems %} {{release.releaseTitle}} {% endfor %} </body> </html> 43
  • 44. FRONT END • Open http://127.0.0.1:8000/ You will be able to see the model data 44