SlideShare a Scribd company logo
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.
templates in Django material : Training available at Baabtra

More Related Content

What's hot

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
Morten Andersen-Gott
ย 
Restful App Engine
Restful App EngineRestful App Engine
Restful App Engine
Ryan 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-slides
MasterCode.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 beyond
David Glick
ย 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
BOSC Tech Labs
ย 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
mcantelon
ย 
Java ap is you should know
Java ap is you should knowJava ap is you should know
Java ap is you should know
Hendrik Ebbers
ย 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the Scenes
Joshua 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 theme
mohd 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.3
Fabien Potencier
ย 
Into The Box 2018 - CBT
Into The Box 2018 - CBTInto The Box 2018 - CBT
Into The Box 2018 - CBT
Ortus Solutions, Corp
ย 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
ย 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
Dave Cross
ย 
Jquery 4
Jquery 4Jquery 4
Jquery 4
Manish Kumar Singh
ย 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
Siarhei Barysiuk
ย 
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
Jeff Durta
ย 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
ย 
Flamingo Hello World Tutorial
Flamingo Hello World TutorialFlamingo Hello World Tutorial
Flamingo Hello World Tutorial
i-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 paginate
Katy Slemon
ย 

What's hot (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
ย 

Similar to templates in Django material : Training available at Baabtra

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
Shrinath Shenoy
ย 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
Ilian Iliev
ย 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade 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 URLconfs
Vincent 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 Engine
Yared Ayalew
ย 
Django
DjangoDjango
Django
Mohamed Ramadan
ย 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
Xiaoqi Zhao
ย 
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptxWRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
WRStmlDSQUmUrZpQ0tFJ4Q_a36bc57fe1a24dd8bc5ba549736e406f_C2-Week2.pptx
salemsg
ย 
Django crush course
Django crush course Django crush course
Django crush course
Mohammed El Rafie Tarabay
ย 
Django
DjangoDjango
Django
Harmeet Lamba
ย 
Django by rj
Django by rjDjango by rj
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
zekeLabs Technologies
ย 
ๅœ‹ๆฐ‘้›ฒ็ซฏๆžถๆง‹ Django + GAE
ๅœ‹ๆฐ‘้›ฒ็ซฏๆžถๆง‹ Django + GAEๅœ‹ๆฐ‘้›ฒ็ซฏๆžถๆง‹ Django + GAE
ๅœ‹ๆฐ‘้›ฒ็ซฏๆžถๆง‹ Django + GAE
Winston Chen
ย 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
Kevin Wu
ย 
Django
DjangoDjango
Django
Ksd Che
ย 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
Ksd Che
ย 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
Felipe Queiroz
ย 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
ย 
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
Leonardo Fernandes
ย 

Similar to templates in Django material : Training available at Baabtra (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
ย 

More from baabtra.com - No. 1 supplier of quality freshers

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
baabtra.com - No. 1 supplier of quality freshers
ย 
Best coding practices
Best coding practicesBest coding practices
Core java - baabtra
Core java - baabtraCore 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 - No. 1 supplier of quality freshers
ย 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
ย 
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
baabtra.com - No. 1 supplier of quality freshers
ย 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php database connectivity
Php database connectivityPhp database connectivity
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
ย 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
ย 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
ย 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
ย 
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
baabtra.com - No. 1 supplier of quality freshers
ย 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
ย 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
ย 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Blue brain
Blue brainBlue brain
5g
5g5g
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Gd baabtra
Gd baabtraGd baabtra

More from 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
ย 

Recently uploaded

THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
indexPub
ย 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
ย 
Bossa Nโ€™ Roll Records by Ismael Vazquez.
Bossa Nโ€™ Roll Records by Ismael Vazquez.Bossa Nโ€™ Roll Records by Ismael Vazquez.
Bossa Nโ€™ Roll Records by Ismael Vazquez.
IsmaelVazquez38
ย 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapitolTechU
ย 
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
Payaamvohra1
ย 
Juneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School DistrictJuneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School District
David Douglas School District
ย 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
ย 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
ย 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
khuleseema60
ย 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
Celine George
ย 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Kalna College
ย 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
ย 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
Kalna College
ย 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
ย 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
ImMuslim
ย 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
ย 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
ย 
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxxSimple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
RandolphRadicy
ย 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
nitinpv4ai
ย 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
Mohammad Al-Dhahabi
ย 

Recently uploaded (20)

THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
THE SACRIFICE HOW PRO-PALESTINE PROTESTS STUDENTS ARE SACRIFICING TO CHANGE T...
ย 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
ย 
Bossa Nโ€™ Roll Records by Ismael Vazquez.
Bossa Nโ€™ Roll Records by Ismael Vazquez.Bossa Nโ€™ Roll Records by Ismael Vazquez.
Bossa Nโ€™ Roll Records by Ismael Vazquez.
ย 
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptxCapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
CapTechTalks Webinar Slides June 2024 Donovan Wright.pptx
ย 
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
NIPER 2024 MEMORY BASED QUESTIONS.ANSWERS TO NIPER 2024 QUESTIONS.NIPER JEE 2...
ย 
Juneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School DistrictJuneteenth Freedom Day 2024 David Douglas School District
Juneteenth Freedom Day 2024 David Douglas School District
ย 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
ย 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
ย 
MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025MDP on air pollution of class 8 year 2024-2025
MDP on air pollution of class 8 year 2024-2025
ย 
How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17How to Manage Reception Report in Odoo 17
How to Manage Reception Report in Odoo 17
ย 
Contiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptxContiguity Of Various Message Forms - Rupam Chandra.pptx
Contiguity Of Various Message Forms - Rupam Chandra.pptx
ย 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
ย 
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx78 Microsoft-Publisher - Sirin Sultana Bora.pptx
78 Microsoft-Publisher - Sirin Sultana Bora.pptx
ย 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
ย 
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
Geography as a Discipline Chapter 1 __ Class 11 Geography NCERT _ Class Notes...
ย 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
ย 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
ย 
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxxSimple-Present-Tense xxxxxxxxxxxxxxxxxxx
Simple-Present-Tense xxxxxxxxxxxxxxxxxxx
ย 
Skimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S EliotSkimbleshanks-The-Railway-Cat by T S Eliot
Skimbleshanks-The-Railway-Cat by T S Eliot
ย 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
ย 

templates in Django material : Training available at Baabtra

  • 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.