templates in Django material : Training available at Baabtra

55

description

Templates in Django - Python, How to use master page in Django using Templates, How to fix TemplateDoesNotExist at error in Django. How to run Django applications in Windows. How a Django view works.

Transcript of templates in Django material : Training available at Baabtra

Page 1: templates in Django material : Training available at Baabtra
Page 2: templates in Django material : Training available at Baabtra

Django framework Training Material

Haris [email protected]/haris.np9twitter.com/np_harisin.linkedin.com/in/harisnp

Page 3: templates in Django material : Training available at Baabtra

Courtesy

• www.djangobook.com

Page 4: templates in Django material : Training available at Baabtra

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

Page 5: templates in Django material : Training available at Baabtra

• 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

Page 6: templates in Django material : Training available at Baabtra

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

Page 7: templates in Django material : Training available at Baabtra

• For creating a new project in Django– django-admin.py startproject mysite

Page 8: templates in Django material : Training available at Baabtra

• Create a view.py (It is for easy to understand and naming convention. You can give any name to the py files)

Page 9: templates in Django material : Training available at Baabtra

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

Page 10: templates in Django material : Training available at Baabtra

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

Page 11: templates in Django material : Training available at Baabtra

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

Page 12: templates in Django material : Training available at Baabtra

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

Page 13: templates in Django material : Training available at Baabtra

views.py

• Here baabtrastudentwebsite is the main folder and is a project (studentweb is an app inside the project)

Page 14: templates in Django material : Training available at Baabtra

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)

Page 15: templates in Django material : Training available at Baabtra

Urls.py

Page 16: templates in Django material : Training available at Baabtra

Running the app

• In the command prompt, type python manage.py runserver

Page 17: templates in Django material : Training available at Baabtra

• Type http://127.0.0.1:8000/home/ in the browser

Page 18: templates in Django material : Training available at Baabtra

• Type http://127.0.0.1:8000/homew/ in the browser

Page 19: templates in Django material : Training available at Baabtra

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.

Page 20: templates in Django material : Training available at Baabtra

• Settings.py

Page 21: templates in Django material : Training available at Baabtra

• 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

Page 22: templates in Django material : Training available at Baabtra

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

Page 23: templates in Django material : Training available at Baabtra

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

Page 24: templates in Django material : Training available at Baabtra

Templates

• Why templates?– For separating the python code and HTML

• Advantages– Any design change will not affect the python code– Separation of duties

Page 25: templates in Django material : Training available at Baabtra

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>

Page 26: templates in Django material : Training available at Baabtra

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.

Page 27: templates in Django material : Training available at Baabtra

How to use template in Django?Type python manage.py shellTemplate 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.

Page 28: templates in Django material : Training available at Baabtra

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

Page 29: templates in Django material : Training available at Baabtra

• The second line creates a template object. If there is an error TemplateSyntaxError is thrown.

• Block tag and template tag are synonymous.

Page 30: templates in Django material : Training available at Baabtra

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)

Page 31: templates in Django material : Training available at Baabtra
Page 32: templates in Django material : Training available at Baabtra

• You can render the same template with multiple contexts.

Page 33: templates in Django material : Training available at Baabtra

Using Templates in views

• Django provides template-loading API• In the settings.py file, the template directory

name is mentioned under TEMPLATE_DIRS tag.

Page 34: templates in Django material : Training available at Baabtra

views.py

• def templatecalling(request): now = datetime.datetime.now()

t = get_template('welcome.html') html = t.render(Context({'current_date': now})) return HttpResponse(html)

Page 35: templates in Django material : Training available at Baabtra

Welcome.html

<html><body>Welcome to baabttra: It is now {{ now }}.</body></html>

Page 36: templates in Django material : Training available at Baabtra

settings.py

Page 37: templates in Django material : Training available at Baabtra

urls.py

Page 38: templates in Django material : Training available at Baabtra

http://127.0.0.1:8000/tempex/

Page 39: templates in Django material : Training available at Baabtra

• 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__))

Page 40: templates in Django material : Training available at Baabtra

• Now run the application again.

Page 41: templates in Django material : Training available at Baabtra

Possible errors

• TemplateDoesNotExist at /tempex/

Page 42: templates in Django material : Training available at Baabtra

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

Page 43: templates in Django material : Training available at Baabtra

Refresh the page

• Please note that in this case we have not given the absolute path.

Page 44: templates in Django material : Training available at Baabtra

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.

Page 45: templates in Django material : Training available at Baabtra

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

Page 46: templates in Django material : Training available at Baabtra

views.py

Page 47: templates in Django material : Training available at Baabtra

Solution

• view.py page

Page 48: templates in Django material : Training available at Baabtra

views.pydef 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)

Page 49: templates in Django material : Training available at Baabtra

urls.py

Page 50: templates in Django material : Training available at Baabtra

templates

Page 51: templates in Django material : Training available at Baabtra

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

Page 52: templates in Django material : Training available at Baabtra

• HTML inside masterpage.htmlThere is no html tags used here. This is from master page

Page 53: templates in Django material : Training available at Baabtra

Result when run

Page 54: templates in Django material : Training available at Baabtra

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

Page 55: templates in Django material : Training available at Baabtra