SlideShare une entreprise Scribd logo
1  sur  55
Django framework
Training Material
Haris NP
haris@baabtra.com
www.facebook.com/haris.np
9
twitter.com/np_haris
in.linkedin.com/in/harisnp
Courtesy
• www.djangobook.com
Django
• It is a web framework
• It follow MVC architecture (MTV architecture)
– Model View Controller
• Model = Database
• View = Presentation
• Controller = Business Logic

– Model Template View
• Model = Database
• Template = Presentation
• View = Business Logic
• In the case of Django View contains the business logic.
It is different from normal MVC nomenclature.
• For a normal HTML web page to output, there must be
four files.
– Models.py = It contains the database objects. It helps you
to write python codes rather than SQL statements
– View.py = It contains the logic
– Ulrs.py = It contains the configuration /urls in the website
– Html (template) = The presentation or what the user sees
• a view is just a Python function that takes
an HttpRequest as its first parameter and
returns an instance of HttpResponse. In order
for a Python function to be a Django view, it
must do these two things. (There are
exceptions, but we’ll get to those later.)
• For creating a new project in Django
– django-admin.py startproject mysite
• Create a view.py (It is for easy to understand
and naming convention. You can give any
name to the py files)
Stupid error that you can make!
• Always tick file extension when you are
programming in Windows . I created a file
name views.py and in fact it was views.py.py. I
kept getting the error
– “ImportError at /hello/
– No module named views
• Even though the error is caused while using
Django (Python framework), it has nothing to
do with Django. You must try importing the
views.py directly in the python command line.
• If you get the above error come and check
whether .pyc file is created for the view. If not
there is something wrong with the file and
how it was defined.
“Welcome to baabtra program”
• Here we are going to teach you how to print
“Welcome to baabtra – Now the time is
*System Time+” using Django framework
(Python)
• There will be 2 files required for this program
• views.py: This file can be present in Main
folder of the project or in an app.
views.py
• Here baabtrastudentwebsite is the main
folder and is a project (studentweb is an app
inside the project)
views.py
• import datetime
• from django.http import HttpResponse
• def hellobaabtra(request):
#This is created for a simple Hello message
return HttpResponse("Hello Baabtra")
• def welcomecurrent_datetime(request):
now = datetime.datetime.now()
html = "<html><body>Welcome to baabttra: It is
now %s.</body></html>" % now
return HttpResponse(html)
Urls.py
Running the app
• In the command prompt, type
python manage.py runserver
• Type http://127.0.0.1:8000/home/ in the
browser
• Type http://127.0.0.1:8000/homew/ in the
browser
How the code works?
• Django starts with Settings.py file.
• When you run python manage.py runserver, the
script looks for a file called settings.py in the
inner baabtrastudentwebsite directory. This file
contains all sorts of configuration for this
particular Django project, all in uppercase:
TEMPLATE_DIRS, DATABASES, etc. The most
important setting is called ROOT_URLCONF.
ROOT_URLCONF tells Django which Python
module should be used as the URLconf for this
Web site.
• Settings.py
• The autogenerated settings.py contains
a ROOT_URLCONF setting that points to the
autogenerated urls.py. Below is a screenshot
from settings.py
• This corresponds the file
/baabtrastudentwebsite/url
• When a request comes in for a particular URL –
say, a request for /hello/ – Django loads the
URLconf pointed to by
the ROOT_URLCONF setting. Then it checks each
of the URLpatterns in that URLconf, in
order, comparing the requested URL with the
patterns one at a time, until it finds one that
matches. When it finds one that matches, it calls
the view function associated with that
pattern, passing it an HttpRequest object as the
first parameter.
• In summary:
– A request comes in to /hello/.
– Django determines the root URLconf by looking at
the ROOT_URLCONF setting.
– Django looks at all of the URLpatterns in the URLconf
for the first one that matches /hello/.
– If it finds a match, it calls the associated view function.
– The view function returns an HttpResponse.
– Django converts the HttpResponse to the proper HTTP
response, which results in a Web page.
Templates
• Why templates?
– For separating the python code and HTML

• Advantages
– Any design change will not affect the python code
– Separation of duties
Example for a template
<html>
<head><title>Ordering notice</title></head>
<body>
<h1>Baabtra Notification</h1>
<p>Dear {{ candidate_name }},</p>
<p>Congragulations! You have been selected by {{ company }}.</p>
<p>Your subjects are</p>
<ul>
{% for subject in subjectlist %}
<li>{{ subject }}</li>
{% endfor %}
</ul>
{% if distinction %}
<p>Great! You have more than 80% marks.</p>
{% else %}
<p>You have cleared all the tests.</p>
{% endif %}
<p>Sincerely,<br />{{ mentor }}</p>
</body>
</html>
Explanation
• Candidate_name is a variable. Any text
surrounded by a pair of braces
(e.g., {{ candidate_name }}) is a variable
• {% if distinction %} is template tag.
How to use template in Django?
Type python manage.py shell
Template system rely on settings.py. Django looks for an environment variable
called DJANGO_SETTINGS_MODULE, which should be set to the import path
of your settings.py. For example, DJANGO_SETTINGS_MODULE might be set
to ‘baabtrastudentwebsite.settings', assuming baabtrastudentwebsite is on
your Python path. While running python, it is better to use python manage.py
shell as it will reduce errors.
You can find the value in manage.py file of the project.
>>> from django import template
>>> t = template.Template('My training centre is {{
name }}.')
>>> c = template.Context({'name': ‘baabtra'})
>>> print t.render(c)
My training centre is baabtra.
>>> c = template.Context(,'name': ‘baabte'})
>>> print t.render(c)
'My training centre is baabte .
• The second line creates a template object. If
there is an error TemplateSyntaxError is
thrown.
• Block tag and template tag are synonymous.
Rendering a template
• Values are passed to template by giving it a context. A
context is simply a set of template variable names and
their associated values. A template uses this to
populate its variables and evaluate its tags.
• Context class is present in django.template
• Render function returns a unicode object and not a
python string.
• We can also pass string as a template argument to the
constructure. For ex. Str_temp ‘My training centre is {{
name --.‘
• t = template.Template(Str_temp)
• You can render the same template with
multiple contexts.
Using Templates in views
• Django provides template-loading API
• In the settings.py file, the template directory
name is mentioned under TEMPLATE_DIRS
tag.
views.py
• def templatecalling(request):
now = datetime.datetime.now()
t = get_template('welcome.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)
Welcome.html

<html><body>Welcome to baabttra: It is now {{ now }}.</body></html>
settings.py
urls.py
http://127.0.0.1:8000/tempex/
• Now if you want to give the relative path, you
can follow the below steps:
– Settings.py
– Please add
• import os.path
• PROJECT_PATH =
os.path.realpath(os.path.dirname(__file__))
• Now run the application again.
Possible errors
• TemplateDoesNotExist at /tempex/
• If we are not giving the absolute path for the
template folder, you need to put the template
under the project folder or app with the same
name as that of project. Our program runs
under the folder with the same name as that
of the project.
Refresh the page 
• Please note that in this case we have not given
the absolute path.
Include Template Tag
• {% include template_name %}
• For example, we want to include a home
template in more than one file. In our
previous example, we want to create a master
page which will be used in two pages.
Problem statement
• Create a master page template which will be
included in two templates. The home template
will have
– This is from master page

• The first and second template will have “This is
first template” and “This is second template”
• ViewName:
v_baabtrainctemplate1, v_baabtrainctemplate2
• Url Name: url_ baabtrainctemplate1, url_
baabtrainctemplate2
views.py
Solution
• view.py page
views.py
def v_baabtrainctemplate1(request):
now = datetime.datetime.now()
t = get_template('firstbaabtra.html')
html = t.render(Context({'now': now}, {'name':'First Name'}))
return HttpResponse(html)
def v_baabtrainctemplate2(request):
now = datetime.datetime.now()
t = get_template('secondbaabtra.html')
html = t.render(Context({'now': now},{'name':'Second Name'}))
return HttpResponse(html)
urls.py
templates
• Code under firstbaabtra.html
<html>
<body>
{% include "masterpage.html" %}
<br>

This is the first template. <br>
Welcome to baabtra: It is now {{ now }}.
</body></html>
• HTML inside masterpage.html
There is no html tags used here.
This is from master page
Result when run
• The author takes corporate trainings in
Android, Java, JQuery, JavaScript and Python. In case
if your organization needs training, please connect
through www.massbaab.com/baabtra.
• Baabtra provides both online and offline trainings for
candidates who want to learn latest programming
technologies , frameworks like
codeigniter, django, android, iphone app
development
• Baabtra also provides basic training in
SQL, .NET, PHP, Java and Python who wants to start
their career in IT.
Django framework tutorial for beginners

Contenu connexe

Tendances

Parallel batch processing with spring batch slideshare
Parallel batch processing with spring batch   slideshareParallel batch processing with spring batch   slideshare
Parallel batch processing with spring batch slideshareMorten Andersen-Gott
 
Restful App Engine
Restful App EngineRestful App Engine
Restful App EngineRyan Morlok
 
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Antonio Peric-Mazar
 
2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slidesMasterCode.vn
 
PloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyondPloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyondDavid Glick
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
Java ap is you should know
Java ap is you should knowJava ap is you should know
Java ap is you should knowHendrik Ebbers
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the ScenesJoshua Long
 
How does get template part works in twenty ten theme
How does get template part works in twenty ten themeHow does get template part works in twenty ten theme
How does get template part works in twenty ten thememohd rozani abd ghani
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Fabien Potencier
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)Dave Cross
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
Flamingo Hello World Tutorial
Flamingo Hello World TutorialFlamingo Hello World Tutorial
Flamingo Hello World Tutoriali-love-flamingo
 
Implement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginateImplement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginateKaty Slemon
 

Tendances (20)

Parallel batch processing with spring batch slideshare
Parallel batch processing with spring batch   slideshareParallel batch processing with spring batch   slideshare
Parallel batch processing with spring batch slideshare
 
Restful App Engine
Restful App EngineRestful App Engine
Restful App Engine
 
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)
 
2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides2 introduction-php-mvc-cakephp-m2-installation-slides
2 introduction-php-mvc-cakephp-m2-installation-slides
 
PloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyondPloneNG: What's new in Plone 4.2, 4.3, and beyond
PloneNG: What's new in Plone 4.2, 4.3, and beyond
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Java ap is you should know
Java ap is you should knowJava ap is you should know
Java ap is you should know
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the Scenes
 
How does get template part works in twenty ten theme
How does get template part works in twenty ten themeHow does get template part works in twenty ten theme
How does get template part works in twenty ten theme
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Jquery 4
Jquery 4Jquery 4
Jquery 4
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
Flamingo Hello World Tutorial
Flamingo Hello World TutorialFlamingo Hello World Tutorial
Flamingo Hello World Tutorial
 
Implement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginateImplement react pagination with react hooks and react paginate
Implement react pagination with react hooks and react paginate
 

Similaire à Django framework tutorial for beginners

Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsVincent Chien
 
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 EngineYared Ayalew
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django projectXiaoqi Zhao
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxsalemsg
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAEWinston Chen
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesLeonardo Fernandes
 

Similaire à Django framework tutorial for beginners (20)

Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfs
 
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
 
Django
DjangoDjango
Django
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
 
Django crush course
Django crush course Django crush course
Django crush course
 
Django
DjangoDjango
Django
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Django
DjangoDjango
Django
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 

Plus de baabtra.com - No. 1 supplier of quality freshers

Plus de baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 

Dernier

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 

Dernier (20)

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 

Django framework tutorial for beginners

  • 1.
  • 2. Django framework Training Material Haris NP haris@baabtra.com www.facebook.com/haris.np 9 twitter.com/np_haris in.linkedin.com/in/harisnp
  • 4. Django • It is a web framework • It follow MVC architecture (MTV architecture) – Model View Controller • Model = Database • View = Presentation • Controller = Business Logic – Model Template View • Model = Database • Template = Presentation • View = Business Logic
  • 5. • In the case of Django View contains the business logic. It is different from normal MVC nomenclature. • For a normal HTML web page to output, there must be four files. – Models.py = It contains the database objects. It helps you to write python codes rather than SQL statements – View.py = It contains the logic – Ulrs.py = It contains the configuration /urls in the website – Html (template) = The presentation or what the user sees
  • 6. • a view is just a Python function that takes an HttpRequest as its first parameter and returns an instance of HttpResponse. In order for a Python function to be a Django view, it must do these two things. (There are exceptions, but we’ll get to those later.)
  • 7. • For creating a new project in Django – django-admin.py startproject mysite
  • 8. • Create a view.py (It is for easy to understand and naming convention. You can give any name to the py files)
  • 9. Stupid error that you can make! • Always tick file extension when you are programming in Windows . I created a file name views.py and in fact it was views.py.py. I kept getting the error – “ImportError at /hello/ – No module named views
  • 10. • Even though the error is caused while using Django (Python framework), it has nothing to do with Django. You must try importing the views.py directly in the python command line.
  • 11. • If you get the above error come and check whether .pyc file is created for the view. If not there is something wrong with the file and how it was defined.
  • 12. “Welcome to baabtra program” • Here we are going to teach you how to print “Welcome to baabtra – Now the time is *System Time+” using Django framework (Python) • There will be 2 files required for this program • views.py: This file can be present in Main folder of the project or in an app.
  • 13. views.py • Here baabtrastudentwebsite is the main folder and is a project (studentweb is an app inside the project)
  • 14. views.py • import datetime • from django.http import HttpResponse • def hellobaabtra(request): #This is created for a simple Hello message return HttpResponse("Hello Baabtra") • def welcomecurrent_datetime(request): now = datetime.datetime.now() html = "<html><body>Welcome to baabttra: It is now %s.</body></html>" % now return HttpResponse(html)
  • 16. Running the app • In the command prompt, type python manage.py runserver
  • 19. How the code works? • Django starts with Settings.py file. • When you run python manage.py runserver, the script looks for a file called settings.py in the inner baabtrastudentwebsite directory. This file contains all sorts of configuration for this particular Django project, all in uppercase: TEMPLATE_DIRS, DATABASES, etc. The most important setting is called ROOT_URLCONF. ROOT_URLCONF tells Django which Python module should be used as the URLconf for this Web site.
  • 21. • The autogenerated settings.py contains a ROOT_URLCONF setting that points to the autogenerated urls.py. Below is a screenshot from settings.py • This corresponds the file /baabtrastudentwebsite/url
  • 22. • When a request comes in for a particular URL – say, a request for /hello/ – Django loads the URLconf pointed to by the ROOT_URLCONF setting. Then it checks each of the URLpatterns in that URLconf, in order, comparing the requested URL with the patterns one at a time, until it finds one that matches. When it finds one that matches, it calls the view function associated with that pattern, passing it an HttpRequest object as the first parameter.
  • 23. • In summary: – A request comes in to /hello/. – Django determines the root URLconf by looking at the ROOT_URLCONF setting. – Django looks at all of the URLpatterns in the URLconf for the first one that matches /hello/. – If it finds a match, it calls the associated view function. – The view function returns an HttpResponse. – Django converts the HttpResponse to the proper HTTP response, which results in a Web page.
  • 24. Templates • Why templates? – For separating the python code and HTML • Advantages – Any design change will not affect the python code – Separation of duties
  • 25. Example for a template <html> <head><title>Ordering notice</title></head> <body> <h1>Baabtra Notification</h1> <p>Dear {{ candidate_name }},</p> <p>Congragulations! You have been selected by {{ company }}.</p> <p>Your subjects are</p> <ul> {% for subject in subjectlist %} <li>{{ subject }}</li> {% endfor %} </ul> {% if distinction %} <p>Great! You have more than 80% marks.</p> {% else %} <p>You have cleared all the tests.</p> {% endif %} <p>Sincerely,<br />{{ mentor }}</p> </body> </html>
  • 26. Explanation • Candidate_name is a variable. Any text surrounded by a pair of braces (e.g., {{ candidate_name }}) is a variable • {% if distinction %} is template tag.
  • 27. How to use template in Django? Type python manage.py shell Template system rely on settings.py. Django looks for an environment variable called DJANGO_SETTINGS_MODULE, which should be set to the import path of your settings.py. For example, DJANGO_SETTINGS_MODULE might be set to ‘baabtrastudentwebsite.settings', assuming baabtrastudentwebsite is on your Python path. While running python, it is better to use python manage.py shell as it will reduce errors. You can find the value in manage.py file of the project.
  • 28. >>> from django import template >>> t = template.Template('My training centre is {{ name }}.') >>> c = template.Context({'name': ‘baabtra'}) >>> print t.render(c) My training centre is baabtra. >>> c = template.Context(,'name': ‘baabte'}) >>> print t.render(c) 'My training centre is baabte .
  • 29. • The second line creates a template object. If there is an error TemplateSyntaxError is thrown. • Block tag and template tag are synonymous.
  • 30. Rendering a template • Values are passed to template by giving it a context. A context is simply a set of template variable names and their associated values. A template uses this to populate its variables and evaluate its tags. • Context class is present in django.template • Render function returns a unicode object and not a python string. • We can also pass string as a template argument to the constructure. For ex. Str_temp ‘My training centre is {{ name --.‘ • t = template.Template(Str_temp)
  • 31.
  • 32. • You can render the same template with multiple contexts.
  • 33. Using Templates in views • Django provides template-loading API • In the settings.py file, the template directory name is mentioned under TEMPLATE_DIRS tag.
  • 34. views.py • def templatecalling(request): now = datetime.datetime.now() t = get_template('welcome.html') html = t.render(Context({'current_date': now})) return HttpResponse(html)
  • 35. Welcome.html <html><body>Welcome to baabttra: It is now {{ now }}.</body></html>
  • 39. • Now if you want to give the relative path, you can follow the below steps: – Settings.py – Please add • import os.path • PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
  • 40. • Now run the application again.
  • 42. • If we are not giving the absolute path for the template folder, you need to put the template under the project folder or app with the same name as that of project. Our program runs under the folder with the same name as that of the project.
  • 43. Refresh the page  • Please note that in this case we have not given the absolute path.
  • 44. Include Template Tag • {% include template_name %} • For example, we want to include a home template in more than one file. In our previous example, we want to create a master page which will be used in two pages.
  • 45. Problem statement • Create a master page template which will be included in two templates. The home template will have – This is from master page • The first and second template will have “This is first template” and “This is second template” • ViewName: v_baabtrainctemplate1, v_baabtrainctemplate2 • Url Name: url_ baabtrainctemplate1, url_ baabtrainctemplate2
  • 48. views.py def v_baabtrainctemplate1(request): now = datetime.datetime.now() t = get_template('firstbaabtra.html') html = t.render(Context({'now': now}, {'name':'First Name'})) return HttpResponse(html) def v_baabtrainctemplate2(request): now = datetime.datetime.now() t = get_template('secondbaabtra.html') html = t.render(Context({'now': now},{'name':'Second Name'})) return HttpResponse(html)
  • 51. • Code under firstbaabtra.html <html> <body> {% include "masterpage.html" %} <br> This is the first template. <br> Welcome to baabtra: It is now {{ now }}. </body></html>
  • 52. • HTML inside masterpage.html There is no html tags used here. This is from master page
  • 54. • The author takes corporate trainings in Android, Java, JQuery, JavaScript and Python. In case if your organization needs training, please connect through www.massbaab.com/baabtra. • Baabtra provides both online and offline trainings for candidates who want to learn latest programming technologies , frameworks like codeigniter, django, android, iphone app development • Baabtra also provides basic training in SQL, .NET, PHP, Java and Python who wants to start their career in IT.