Module 2notes
Module 2notes
Module 2
2.1 The Django Template System
A Django template is a string of text that is intended to separate the presentation of a
document from its data. A template defines placeholders and various bits of basic logic (i.e.,
template tags) that regulate how the document should be displayed.
Example: The template describes an HTML page that thanks a person for placing an order with
a company.
Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable. This
means “insert the value of the variable with the given name.
DSATM Page 1
BANGALOREBAN
GALORE
Full Stack Development Module 2
Any text that’s surrounded by curly braces and percent signs (e.g., {% if ordered_
warranty %}) is a template tag.
This example template contains two tags: the {% for item in item_list %} tag (a for tag)
and the {% if ordered_warranty %} tag (an if tag).
Finally, the second paragraph of this template has an example of a filter, with which you
can alter the display of a variable. In this example, {{ ship_date|date:"F j, Y" }}, we’re
passing the ship_date variable to the date filter, giving the date filter the argument "F j,
Y". The date filter formats dates in a given format, as specified by that argument. Filters
are attached using a pipe character (|), as a reference to Unix pipes
1. Create a Template object by providing the raw template code as a string. Django also offers a
way to create Template objects by designating the path to a template file on the filesystem;
2. Call the render() method of the Template object with a given set of variables (i.e., the context).
This returns a fully rendered template as a string, with all of the variables and block tags
evaluated according to the context.
This constructor takes one argument - raw template code. There are three formats to define
template objects discussed below.
2. Three dot (…)- multiple statements these are inserted by the python shell and are not part of
input.
3. Triple quote (”””) - marks to designate the string, because it wraps over multiple lines.
DSATM Page 2
BANGALOREBAN
GALORE
Full Stack Development Module 2
2.4 TemplateSyntaxError:
from django.template import Template
The system raises a TemplateSyntaxError exception for any of the following cases:
• Invalid filters
• Unclosed block tags (for block tags that require closing tags)
To write a template, create a Template object, create a Context, and call the
render() method
DSATM Page 3
BANGALOREBAN
GALORE
Full Stack Development Module 2
Output:
• First, we import the classes Template and Context, which both live in the module
django.template.
• We save the raw text of our template into the variable raw_template.
• Next, we create a template object, t, by passing raw_template to the Template class constructor.
• We import the datetime module from Python’s standard library, because we’ll need it in the
following statement.
• Then, we create a Context object, c. The Context constructor takes a Python dictionary, which
maps variable names to values.
• Finally, we call the render() method on our template object, passing it the context. This returns
the rendered template—that is, it replaces template variables with the actual values of the
variables, and it executes any block tags. The warranty paragraph was displayed because the
DSATM Page 4
BANGALOREBAN
GALORE
Full Stack Development Module 2
ordered_warranty variable evaluated to True. Also note the date, April 2, 2009, which is
displayed according to the format string 'F j, Y'.
Example:
It’s more efficient to create the Template object once, and then call render() on it multiple times:
Example:
DSATM Page 5
BANGALOREBAN
GALORE
Full Stack Development Module 2
1. Dictionary lookup: Passing a Python dictionary to a template. To access the values of that
dictionary by dictionary key, use a doT(.):
Example: A Python datetime.date object has year, month, and day attributes, and you can use a
dot to access those attributes in a Django template.
Example: Each Python string has the methods upper() and isdigit(), and you can call those in
Django templates using the same dot syntax:
DSATM Page 6
BANGALOREBAN
GALORE
Full Stack Development Module 2
4. List-index lookup: ( .) dots are also used to access list indices. Negative list indices are not
allowed.
Example:
Example: The following example uses {{ person.name.upper }}, which translates into a
dictionary lookup (person['name']) and then a method call (upper())
c = Context({'person': person})
t.render(c)
1. if/else
2. for
3. ifequal/ifnotequal
4. comments
1. if/else: The {% if %} tag evaluates a variable, and if that variable is “true, the system will
display everything between {% if %} and {% endif %}.
Example:
DSATM Page 7
BANGALOREBAN
GALORE
Full Stack Development Module 2
Example
2. for tag:
The {% for %} tag allows you to loop over each item in a sequence.
X is the name of the variable to use for a particular cycle of the loop.
Each time through the loop, the template system will render everything between {% for %} and
{% endfor %}.
DSATM Page 8
BANGALOREBAN
GALORE
Full Stack Development Module 2
Example: To display a list of athletes given a variable athlete_list:
There is no support for “breaking out” of a loop before the loop is finished. Similarly, there is no
support for a “continue” statement that would instruct the loop processor to return immediately
to the front of the loop.
Forloop attributes:
forloop.counter is always set to an integer representing the number of times the loop has
been entered. This is one-indexed, so the first time through the loop, forloop.counter will
be set to 1. Here’s an example: {% for item in todo_list %}
{% endfor %}
• forloop.counter0 is like forloop.counter, except it’s zero-indexed. Its value will be set to 0 the
first time through the loop.
• forloop.revcounter is always set to an integer representing the number of remaining items in
the loop. The first time through the loop, forloop.revcounter will be set to the total number of
DSATM Page 9
BANGALOREBAN
GALORE
Full Stack Development Module 2
items in the sequence you’re traversing. The last time through the loop, forloop.revcounter will
be set to 1.
• forloop.revcounter0 is like forloop.revcounter, except it’s zero-indexed. The first time through
the loop, forloop.revcounter0 will be set to the number of elements in the sequence minus 1. The
last time through the loop, it will be set to 0.
• forloop.first is a Boolean value set to True if this is the first time through the loop. This is
convenient for special casing:
• forloop.last is a Boolean value set to True if this is the last time through the loop. A common
use for this is to put pipe characters between a list of links:
forloop.parentloop is a reference to the forloop object for the parent loop, in case of nested
loops.
3. ifequal/ifnotequal: The ifequal tag compares two values and displays everything between
ifequal and endifequal if the values are equal.
Example:
DSATM Page 10
BANGALOREBAN
GALORE
Full Stack Development Module 2
{# This is a comment #}
Filters: Template filters are simple ways of altering the value of variables before they’re
displayed.
{{ name|lower }}
This displays the value of the {{ name }} variable after being filtered through the lower filter,
which converts text to lowercase. Use a pipe (|) to apply a filter.
Filters can be chained—that is, the output of one filter is applied to the next. Here’s a common
idiom for escaping text contents and then converting line breaks to <p>tags:
{{ my_text|escape|linebreaks }}
Some filters take arguments. A filter argument looks like this:
DSATM Page 11
BANGALOREBAN
GALORE
Full Stack Development Module 2
{{ bio|truncatewords:"30" }}
This displays the first 30 words of the bio variable. Filter arguments are always in double quotes.
Types of filters;
• addslashes: Adds a backslash before any backslash, single quote, or double quote. This is
useful if the produced text is included in a JavaScript string.
• date: Formats a date or datetime object according to a format string given in the parameter, for
example: {{ pub_date|date:"F j, Y" }} Format strings are defined in Appendix F.
• escape: Escapes ampersands, quotes, and angle brackets in the given string.
This is useful for sanitizing user-submitted data and for ensuring data is valid XML or XHTML.
Specifically, escape makes these conversions:
• Converts & to amp;
• Converts < to lit;
• Converts > to gt;
• Converts " (double quote) to " ;
• Converts ' (single quote) to '
• length: Returns the length of the value
2.9 Template Loading:
Django provides a convenient and powerful API for loading templates from disk, with the
goal of removing redundancy both in your template-loading calls and in your templates
themselves.
In order to use this template-loading API, first you’ll need to tell the framework where
you store your templates. The place to do this is in your settings file.
A Django settings file is the place to put configuration for your Django instance.
The setting tells Django’s template-loading mechanism where to look for templates. By default,
it’s an empty tuple. Pick a directory where you’d like to store your templates and add it to
TEMPLATE_DIRS, like so:
You can specify any directory you want, as long as the directory and templates within that
directory are readable by the user account under which your Web server runs.
DSATM Page 12
BANGALOREBAN
GALORE
Full Stack Development Module 2
If you want to avoid this error, you can make TEMPLATE_DIRS a list instead of a tuple,
because single-element lists don’t require a trailing comma:
This example uses the “magic” Python variable file , which is automatically set to the file name of
the Python module in which the code lives.
DSATM Page 13
BANGALOREBAN
GALORE
Full Stack Development Module 2
(Note: Instead of above program you can also write lab program 5)
2.9.1: The include Template Tag is built in function.
{% include %}.
This tag allows you to include the contents of another template.
The argument to the tag should be the name of the template to include, and the template
name can be either a variable or a hard-coded (quoted) string, in either single or double
quotes.
Example:
These two examples include the contents of the template nav.html. The examples are equivalent
and illustrate that either single or double quotes are allowed:
{% include 'nav.html' %} {% include "nav.html" %}
2.10 Template Inheritance:
To reduce redundancy and duplication of common pages the template inheritance is
required.
Template inheritance lets you build a base “skeleton” template that contains all the
common parts of your site and defines “blocks” that child templates can override
Example: Lab program 6
DSATM Page 14
BANGALOREBAN
GALORE
Full Stack Development Module 2
Interacting with a Database: Models
The MTV Development Pattern: There are three pieces together—data access logic, business
logic, and presentation logic— comprise a concept that’s sometimes called the Model-View-
Controller (MVC) pattern software architecture.
Django follows this MVC pattern closely enough that it can be called an MVC framework. T
The M, V, and C break down in Django:
• M, the data-access portion, is handled by Django’s database layer,
• V, the portion that selects which data to display and how to display it, is handled by
views and templates.
• C, the portion that delegates to a view depending on user input, is handled by the
framework itself by following your URLconf and calling the appropriate Python function for the
given URL.
Django has been referred to as an MTV framework. In the MTV development pattern,
• M stands for “Model,” the data access layer. This layer contains anything and
everything about the data: how to access it, how to validate it, which behaviors it has, and the
relationships between the data.
• T stands for “Template,” the presentation layer. This layer contains presentation-related
decisions: how something should be displayed on a Web page or other type of document.
• V stands for “View,” the business logic layer. This layer contains the logic that accesses
the model and defers to the appropriate template(s). You can think of it as the bridge between
models and templates.
Configuring the Database
We need to tell Django which database server to use and how to connect to it.
Database configuration lives in the Django settings file, called settings.py by default. Edit that
file and look for the database settings:
DATABASE_ENGINE = ' '
DATABASE_NAME = ' '
DATABASE_USER = ' '
DATABASE_PASSWORD =’ ’
DATABASE_HOST = ' ‘
DATABASE_PORT = ' '
DSATM Page 15
BANGALOREBAN
GALORE
Full Stack Development Module 2
• DATABASE_ENGINE tells Django which database engine to use. If you’re using a database
with Django, DATABASE_ENGINE must be set to one of the strings shown in Table
DATABASE_NAME tells Django the name of your database. If you’re using SQLite,
specify the full filesystem path to the database file on your filesystem (e.g.,
'/home/django/mydata.db').
DATABASE_USER tells Django which username to use when connecting to your
database. If you’re using SQLite, leave this blank.
DATABASE_PASSWORD tells Django which password to use when connecting to
your database. If you’re using SQLite or have an empty password, leave this blank.
DATABASE_HOST tells Django which host to use when connecting to your database.
If your database is on the same computer as your Django installation (i.e., localhost),
leave this blank. If you’re using SQLite, leave this blank.
MySQL is a special case here. If this value starts with a forward slash (/) and you’re
using MySQL, MySQL will connect via a Unix socket to the specified socket,
For example: DATABASE_HOST = '/var/run/mysql' If you’re using MySQL
and this value doesn’t start with a forward slash, then this value is assumed to be the host.
• DATABASE_PORT tells Django which port to use when connecting to your database.
If you’re using SQLite, leave this blank.
Type these commands to test your database configuration:
DSATM Page 16
BANGALOREBAN
GALORE
Full Stack Development Module 2
• An author has a salutation (e.g., Mr. or Mrs.), a first name, a last name, an email
address, and a headshot photo.
• A publisher has a name, a street address, a city, a state/province, a country, and a Web
site.
• A book has a title and a publication date. It also has one or more authors (a many-
tomany relationship with authors) and a single publisher (a one-to-many relationship—aka
foreign key—to publishers)
The first step in using this database layout with Django is to express it as Python code. In the
models.py file that was created by the startapp command, enter the following:
The first thing to notice is that each model is represented by a Python class that is a
subclass of django.db.models. Model. The parent class, Model, contains all the machinery
necessary to make these objects capable of interacting with a database—and that leaves our
models responsible solely for defining their fields, in a nice and compact syntax
Creating a Database:
Each model generally corresponds to a single database table, and each attribute on a
model generally corresponds to a column in that database table. The attribute name corresponds
to the column’s name, and the type of field (e.g., CharField) corresponds to the database column
type (e.g., varchar).
For example: the Publisher model is equivalent to the following table (assuming PostgreSQL
CREATE TABLE syntax):
We do that by adding the books app to the list of installed apps in the settings file. Edit the
settings.py file again, and look for the INSTALLED_APPS setting. INSTALLED_APPS tells
Django which apps are activated for a given project. By default, it looks like this.
'mysite.books' refers to the books app we’re working on. Each app in INSTALLED_APPS is
represented by its full Python path.
The validate command checks whether your models’ syntax and logic are correct. If all is well,
you’ll see the message 0 errors found. If you don’t, make sure you typed in the model code
correctly. The error output should give you helpful information about what was wrong with the
code.
If your models are valid, run the following command for Django to generate CREATE TABLE
statements for your models in the books app
In this command, books is the name of the app. It’s what you specified when you ran the command
manage.py startapp. When you run the command, you should see something like this: BEGIN
Selecting Objects:
Deleting Objects:
2. Run manage.py sqlall [yourapp] to see the new CREATE TABLE statement for the model. Note the
column definition for the new field.
3. Start your database’s interactive shell. Execute an ALTER TABLE statement that adds your new
column.
Then run the command manage.py sqlall books to see the CREATE TABLE statement. It would look
something like this:
2. Removing Fields:
1. Remove the field from your model and restart the Web server.
2. Remove the column from your database, using a command like this:
Because many-to-many fields are different from normal fields, the removal process is different:
1. Remove the ManyToManyField from your model and restart the Web server.
2. Remove the many-to-many table from your database, using a command like this:
1. Remove the model from your models.py file and restart the Web server.
2. Remove the table from your database, using a command like this: