SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
Morteza Zohoori Shoar
 
Django Mongodb Engine
Django Mongodb EngineDjango Mongodb Engine
Django Mongodb Engine
Flavio Percoco Premoli
 
Django and Mongoengine
Django and MongoengineDjango and Mongoengine
Django and Mongoengine
austinpublic
 
Django
DjangoDjango
Django
Kangjin Jun
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
Django a whirlwind tour
Django   a whirlwind tourDjango   a whirlwind tour
Django a whirlwind tour
Brad Montgomery
 
Django
DjangoDjango
Django
Abhijeet Shekhar
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Omnia Helmi
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
Simon Willison
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
Hannes Hapke
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
Théodore Biadala
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
Hassan Abid
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
funkatron
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Building Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoBuilding Pluggable Web Applications using Django
Building Pluggable Web Applications using Django
Lakshman Prasad
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
Felipe Queiroz
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Bert Wijnants
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 
Django and Mongoengine
Django and MongoengineDjango and Mongoengine
Django and Mongoengine
austinpublic
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
toddbr
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
Hannes Hapke
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
Théodore Biadala
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
Hassan Abid
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
funkatron
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Building Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoBuilding Pluggable Web Applications using Django
Building Pluggable Web Applications using Django
Lakshman Prasad
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
Bert Wijnants
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 

Similar to Tango with django (20)

django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Jagdeep Singh Malhi
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
Edureka!
 
templates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtratemplates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtra
baabtra.com - No. 1 supplier of quality freshers
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
railsbootcamp
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
Srinivasa GV
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
Max Kleiner
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Udit Gangwani
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
zekeLabs Technologies
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
George Nguyen
 
Django Documentation
Django DocumentationDjango Documentation
Django Documentation
Ying wei (Joe) Chou
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
 
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
PyCaret_PedramJahangiryTUTORIALPYTHON.pdfPyCaret_PedramJahangiryTUTORIALPYTHON.pdf
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
wpanjikresno
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
Winston Chen
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
Edureka!
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
railsbootcamp
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim Rocha
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
Srinivasa GV
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
Max Kleiner
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Udit Gangwani
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
George Nguyen
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
Ricardo Soares
 
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
PyCaret_PedramJahangiryTUTORIALPYTHON.pdfPyCaret_PedramJahangiryTUTORIALPYTHON.pdf
PyCaret_PedramJahangiryTUTORIALPYTHON.pdf
wpanjikresno
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
Winston Chen
 
Ad

More from Rajan Kumar Upadhyay (8)

Speed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times fasterSpeed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times faster
Rajan Kumar Upadhyay
 
RPA & Supply Chain
RPA  &  Supply ChainRPA  &  Supply Chain
RPA & Supply Chain
Rajan Kumar Upadhyay
 
Features of globalization and india in global economy
Features of globalization and india in global economyFeatures of globalization and india in global economy
Features of globalization and india in global economy
Rajan Kumar Upadhyay
 
State of Retail E-commerce In India
State of Retail E-commerce In IndiaState of Retail E-commerce In India
State of Retail E-commerce In India
Rajan Kumar Upadhyay
 
Hadoop & distributed cloud computing
Hadoop & distributed cloud computingHadoop & distributed cloud computing
Hadoop & distributed cloud computing
Rajan Kumar Upadhyay
 
Nextop Cloud computing Platform
Nextop Cloud computing PlatformNextop Cloud computing Platform
Nextop Cloud computing Platform
Rajan Kumar Upadhyay
 
Data analysis & decisions
Data analysis & decisionsData analysis & decisions
Data analysis & decisions
Rajan Kumar Upadhyay
 
Business Intelligence & its Best Practices
Business Intelligence & its Best PracticesBusiness Intelligence & its Best Practices
Business Intelligence & its Best Practices
Rajan Kumar Upadhyay
 
Speed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times fasterSpeed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times faster
Rajan Kumar Upadhyay
 
Features of globalization and india in global economy
Features of globalization and india in global economyFeatures of globalization and india in global economy
Features of globalization and india in global economy
Rajan Kumar Upadhyay
 
State of Retail E-commerce In India
State of Retail E-commerce In IndiaState of Retail E-commerce In India
State of Retail E-commerce In India
Rajan Kumar Upadhyay
 
Hadoop & distributed cloud computing
Hadoop & distributed cloud computingHadoop & distributed cloud computing
Hadoop & distributed cloud computing
Rajan Kumar Upadhyay
 
Business Intelligence & its Best Practices
Business Intelligence & its Best PracticesBusiness Intelligence & its Best Practices
Business Intelligence & its Best Practices
Rajan Kumar Upadhyay
 
Ad

Recently uploaded (20)

Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 

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