Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Django Framework

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44
At a glance
Powered by AI
Django is a popular Python web framework that enables rapid development of secure and maintainable websites. It follows the MVT pattern and includes features like authentication, administration, and reusable components.

Django is a Python-based web framework that allows for rapid development of web applications. It was initially developed in 2003 and open sourced in 2005. Some key features include being highly scalable, secure, and providing many built-in utilities.

Django follows the MVT (Model View Template) architecture pattern. The model handles the data and database interactions. Views control application logic and presentation. Templates define reusable presentation elements.

Django FRAMEWORK

Django is an extremely popular and fully featured server-side web framework,


written in Python. Django is a high-level Python web framework that enables rapid
development of secure and maintainable websites. It is free and open source, has a
thriving and active community, great documentation, and many options for free
and paid-for support.

Django was initially developed between 2003 and 2005 by a web team who were
responsible for creating and maintaining newspaper websites. After creating a
number of sites, the team began to factor out and reuse lot of common code and
design patterns. This common code evolved into a generic web development
framework, which was open-sourced as the "Django" project in July 2005.

Django has continued to grow and improve, from its first milestone release (1.0) in
September 2008 through to the recently-released version 2.0 (2017). Each release
has added new functionality and bug fixes, ranging from support for new types of
databases, template engines, and caching, through to the addition of "generic" view
functions and classes (which reduce the amount of code that developers have to
write for a number of programming tasks).

Ridiculously fast.

Django was designed to help developers take applications from concept to


completion as quickly as possible.

Reassuringly secure.

Django takes security seriously and helps developers avoid many common security
mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and

Ipsr.edu.in Django 1
click jacking. Its user authentication system provides a secure way to manage user
accounts and passwords.

Exceedingly scalable.

Some of the busiest sites on the Web leverage Django’s ability to quickly and
flexibly scale.

Fully loaded.

Django includes dozens of extras you can use to handle common Web
development tasks. Django takes care of user authentication, content
administration, site maps, RSS feeds, and many more tasks — right out of the box

Incredibly versatile.

Companies, organizations and governments have used Django to build all sorts of
things — from content management systems to social networks to scientific
computing platforms.

Django Architecture

Django follows a mvc-mvt architecture.

MVC stands for Model View Controller. It is used for developing the web
publications, where we break the code into various segments. Here we have 3
segments, model view and a controller.

Model – Model is used for storing and maintaining your data. It is the backend
where your database is defined.

Ipsr.edu.in Django 2
Views – In Django templates, views are in html. View is all about the presentation
and it is not at all aware of the backend. Whatever the user is seeing, it is referred
as a view.

Controller – Controller is a business logic which will interact with the model and
the view.

Now that we have understood MVC, lets learn about Django MVT pattern.

MVT stands for Model View Template. In MVT, there is a predefined template for
user interface. Let’s take an example, say you want to write several static html
forms like hello user 1, hello user2 and so on. With template, you will be having
only one file that prints hello along with the variable name. Now this variable will
be substituted in that particular template using some jinja logic. That’s the magic
of template, you don’t need to rewrite the code again n again!

Now you might be wondering where is the controller?

In the case of MVT, Django itself takes care of the controller part, it’s inbuilt.

Moving ahead in Django tutorial, let’s understand how things work internally.

Ipsr.edu.in Django 3
In the above image, template is your front end which will interact with the view
and the model will be used as a backend. Then view will access both the model and
the templates and maps it to a url. After that, Django plays the role of controller
and serves it to the user.

INSTALLATION

Install django using pip

Being a Python Web framework, Django requires Python. Ensure that you install
python on your machine(https://www.python.org/downloads/windows/).

Pip install django

You can also install a very specific version. I will be using 1.9 for this tutorial
series. If you wanted to use that exact version:

pip install Django==1.9

Next step here is for us to create a project.

Note

Projects vs. apps

An app is a Web application that does something – e.g., a Weblog system, a


database of public records or a simple poll app. A project is a collection of
configuration and apps for a particular website. A project can contain multiple
apps. An app can be in multiple projects.

Ipsr.edu.in Django 4
Navigate via the terminal or command prompt to an area where you want to work
on your project, then do:

django-admin startproject project_name

Eg: django-admin startproject myproject

This will create a directory called myproject . Within that directory, you have
another one called myproject, along with a manage.py file. The manage.py file lets
you easily interact with your project via the command line.

The contents of the second myproject directory contain your settings and urls
mainly.

myproject/ - Simple container, Call whatever you want.

manage.py - Lets you interact with your project via the command line.

myproject / - Actual project directory.

__init__.py - Tells python this is a Python package.

settings.py - Settings for the project.

urls.py - URL rules. Django docs aptly describes as your table of


contents.

wsgi.py - WSGI magic begins here. Worry about this when it comes time
to actually deploy to a server

Ipsr.edu.in Django 5
Change the working directory to your project directory(cd myproject) then run the
server using

python manage.py runserver

Copy and paste the url on your web brower .The result will be

Ipsr.edu.in Django 6
Creating App

To create your app, make sure you’re in the same directory as manage.py and type
this command:

python manage.py startapp app_name

Eg:python manage.py startapp myapp

That’ll create a directory myapp, which is laid out like this:

myapp/

__init__.py

Ipsr.edu.in Django 7
admin.py

apps.py

migrations/

__init__.py

models.py

tests.py

views.py

VIEWS

As said earlier in Django templates, views are in html. View is all about the
presentation and it is not at all aware of the backend.

For creating a new view modify the views.py inside myapp

This is the simplest view possible in Django. To call the view, we need to map it to
a URL - and for this we need a URLconf.

A URLconf is like a table of contents for your Django-powered web site.


Basically, it’s a mapping between URLs and the view functions that should be
called for those URLs. It’s how you tell Django, “For this URL, call this code, and

Ipsr.edu.in Django 8
for that URL, call that code.” For example, when somebody visits the URL /foo/,
call the view function foo_view(), which lives in the Python module views.py.

To create a URLconf in the myapp directory, create a file called urls.py

The next step is to point the root URLconf at the webapp.urls module. Open your
myproject/urls.py file and write the below code:

Let’s step through this code one line at a time:

The first line imports two functions from the django.conf.urls module:
include which allows you to include a full Python import path to another URLconf
module, and url which uses a regular expression to pattern match the URL in your
browser to a module in your Django project.

Ipsr.edu.in Django 9
The second line calls the function admin from the django.contrib module. This
function is called by the include function to load the URLs for the Django admin
site.

The third line is urlpatterns – a simple list of url() instances.

The main thing to note here is the variable urlpatterns, which Django expects to
find in your URLconf module. This variable defines the mapping between URLs
and the code that handles those URLs. To add a URL and view to the URLconf,
just add a mapping between a URL pattern and the view function.

Here’s how to hook in our hello world view :

We are now done with the coding part! Let’s now start the server and see what
happens. To start the server

Python manage.py runserver

The result will be

Ipsr.edu.in Django 10
URLPATTERN

Django removes the slash from the front of every incoming URL before it checks the
URLpatterns. This means that our URLpattern doesn’t include the leading slash in
/hello/. At first, this may seem unintuitive, but this requirement simplifies things – such
as the inclusion of URLconfs within other URLconfs

The pattern includes a caret (^) and a dollar sign ($). These are regular expression
characters that have a special meaning: the caret means “require that the pattern
matches the start of the string,” and the dollar sign means “require that the pattern
matches the end of the string.”

This concept is best explained by example. If we had instead used the pattern
^hello/(without a dollar sign at the end), then any URL starting with /hello/ would
match, such as /hello/foo and /hello/bar, not just /hello/.

Ipsr.edu.in Django 11
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would
match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used
hello/, without a caret or dollar sign, then any URL containing hello/ would match,
such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only
the URL /hello/ matches – nothing more, nothing less.

Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice
to have the flexibility to perform more sophisticated matches. You may be wondering
what happens if someone requests the URL /hello (that is, without a trailing slash).
Because our URLpattern requires a trailing slash, that URL would not match.
However, by default, any request to a URL that doesn’t match a URLpattern and
doesn’t end with a slash will be redirected to the same URL with a trailing slash (This
is regulated by the APPEND_SLASH Django setting).

The other thing to note about this URLconf is that we’ve passed the hello view
function as an object without calling the function. This is a key feature of Python (and
other dynamic languages): functions are first-class objects, which means you can pass
them around just like any other variables

Regular Expressions

Regular expressions (or regexes) are a compact way of specifying patterns in text.
While Django URLconfs allow arbitrary regexes for powerful URL matching, you’ll
probably only use a few regex symbols in practice.

Ipsr.edu.in Django 12
Symbol Matches
. (dot) Any single character
\d Any single digit
[A-Z] Any character between A and Z
(uppercase)
[a-z] Any character between a and z
(lowercase)
[A-Za-z] Any character between a and z (case-
insensitive)
+ One or more of the previous expression
(e.g., \d+ matches one or more digits)
[^/]+ One or more characters until (and not
including) a forward slash
? Zero or one of the previous expression
(e.g., \d? matches zero or one digits)
* Zero or more of the previous expression
(e.g., \d* matches zero, one or more
than one digit)
{1,3} Between one and three (inclusive) of the
previous expression (e.g., \d{1,3}
matches one, two or three digits)

Ipsr.edu.in Django 13
DYNAMIC CONTENT WITH VIEW

The “Hello world” view was instructive in demonstrating the basics of how
Django works, but it wasn’t an example of a dynamic web page, because the
content of the page is always the same. Every time you view /hello/, you’ll see the
same thing; it might as well be a static HTML file.

Now lets create a dynamic view witch shows the current date and time. This
new view needs to do two things: calculate the current date and time, and return an
HttpResponse containing that value. If you have experience with Python, you
know that Python includes a datetime module for calculating dates. Here’s a
demonstration using the Python interactive interpreter.

Let’s step through the changes we’ve made to views.py to accommodate the
current_datetime view.

We’ve added an import datetime to the top of the module, so we can calculate
dates. The new getCurrentDateAndTime function calculates the current date and
time, as a datetime.datetime object, and stores that as the local variable now.

The second line of code within the view constructs an HTML response using
Python’s “format-string” capability. The %s within the string is a placeholder, and
the percent sign after the string means “Replace the %s in the preceding string with

Ipsr.edu.in Django 14
the value of the variable now.” The now variable is technically a datetime.datetime
object, not a string, but the %s format character converts it to its string
representation, which is something like “2017-05-20 14:32:25.412665“. This will
result in an HTML string such as “It is now 2017-05-20 14:32:25.412665.“.

Finally, the view returns an HttpResponse object that contains the generated
response – just as we did in hello. After adding that to views.py, add the
URLpattern to urls.py to tell Django which URL should handle this view

DYNAMIC URLS

In our current_datetime view, the contents of the page – the current


date/time – were dynamic, but the URL (/time/) was static. In most dynamic web
applications though, a URL contains parameters that influence the output of the
page. For example, an online bookstore might give each book its own URL, like
/books/243/ and /books/81196/.

Let’s create a third view that displays the current date and time offset by a certain
number of hours. The goal is to craft a site in such a way that the page /time/plus/1/
displays the date/time one hour into the future. the page /time/plus/2/ displays the
date/time two hours into the future.

Ipsr.edu.in Django 15
Now the views.py will be

The view function, hours_ahead, takes two parameters: request and offset:

request is an HttpRequest object, just as in hello and current_datetime. Each view


always takes an HttpRequest object as its first parameter. Offset is the string
captured by the parentheses in the URLpattern. For example, if the requested URL
were /time/plus/3/, then offset would be the string ‘3’. If the requested URL were
/time/plus/21/, then offset would be the string ’21’. Note that captured values will
always be Unicode objects, not integers, even if the string is composed of only
digits, such as ’21’. And of course you should define the url pattern for
hours_ahead function like

Ipsr.edu.in Django 16
URLpattern is a regular expression; hence, we can use the regular expression
pattern \d+ to match one or more digits: This new URLpattern will match any URL
such as /time/plus/2/, /time/plus/25/, or even /time/plus/100000000000/. Come to
think of it, let’s limit it so that the maximum allowed offset is something
reasonable.

In this example, we will set a maximum 99 hours by only allowing either one- or
two-digit numbers – and in regular expression syntax, that translates into \d{1,2}:

Django MODELS.

In modern web applications, the arbitrary logic often involves interacting with a
database. Behind the scenes, a database-driven web site connects to a database
server, retrieves some data out of it, and displays that data on a web page. The site
might also provide ways for site visitors to populate the database on their own.

Many complex web sites provide some combination of the two. Amazon.com, for
instance, is a great example of a database-driven site. Each product page is
essentially a query into Amazon’s product database formatted as HTML, and when
you post a customer review, it gets inserted into the database of reviews.

Django is well suited for making database-driven web sites, because it comes with
easy yet powerful tools for performing database queries using Python.

Configuring the Database.

First, let’s explore the initial configuration that was added to settings.py when we
created the application:

Ipsr.edu.in Django 17
The default setup is pretty simple. Here’s a rundown of each setting:

ENGINE tells Django which database engine to use. As we are using SQLite in the
examples in this book, we will leave it to the default django.db.backends.sqlite3.

NAME tells Django the name of your database. For example: 'NAME': 'mydb',

Defining Django Models in Python.

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:

Ipsr.edu.in Django 18
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.

All the code we need to write to have basic data access with Django. 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

Ipsr.edu.in Django 19
Model Fields

Field Options

https://docs.djangoproject.com/en/2.0/ref/models/fields/#model-field-types

Option Explanation
Field.null If True, Django will store empty values as NULL in the
database. Default is False.
Field.blank If True, the field is allowed to be blank. Default is False.
Note that this is different than null. null is purely
database-related, whereas blank is validation-related. If
a field has blank=True, form validation will allow entry
of an empty value. If a field has blank=False, the field
will be required.
Field.choices An iterable (e.g., a list or tuple) consisting itself of
iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to
use as choices for this field. If this is given, the default
form widget will be a select box with these choices
instead of the standard text field.
The first element in each tuple is the actual value to be
set on the model, and the second element is the human-
readable name
Field.db_column The name of the database column to use for this field. If
this isn’t given, Django will use the field’s name
Field.default The default value for the field. This can be a value or a
callable object. If callable it will be called every time a
new object is created. The default can’t be a mutable

Ipsr.edu.in Django 20
object (model instance, list, set, etc.)
Field.editable If False, the field will not be displayed in the admin or
any other ModelForm. They are also skipped during
model validation. Default is True.
Field.error_messages The error_messages argument lets you override the
default messages that the field will raise. Pass in a
dictionary with keys matching the error messages you
want to override.
Error message keys include null, blank, invalid,
invalid_choice, unique, and unique_for_date.
Field.help_text Extra “help” text to be displayed with the form widget
Field.primary_key If True, this field is the primary key for the model.
If you don’t specify primary_key=True for any field in
your model, Django will automatically add an
AutoField to hold the primary key, so you don’t need to
set primary_key=True on any of your fields unless you
want to override the default primary-key behavior.
Field.unique If True, this field must be unique throughout the table.
Field.unique_for_date Set this to the name of a DateField or DateTimeField to
require that this field be unique for the value of the date
field.
For example, if you have a field title that has
unique_for_date="pub_date", then Django wouldn’t
allow the entry of two records with the same title and
pub_date.
Field.unique_for_month Like unique_for_date, but requires the field to be unique

Ipsr.edu.in Django 21
with respect to the month
Field.unique_for_year Like unique_for_date and unique_for_month
Field.validators A list of validators to run for this field

Field Types

AutoField An IntegerField that automatically increments according to


available IDs. You usually won’t need to use this directly; a
primary key field will automatically be added to your model
if you don’t specify otherwise
BigAutoField A 64-bit integer, much like an AutoField except that it is
guaranteed to fit numbers from 1 to 9223372036854775807
BigIntegerField A 64-bit integer, much like an IntegerField except that it is
guaranteed to fit numbers from -9223372036854775808 to
9223372036854775807. The default form widget for this
field is a TextInput.
BooleanField A true/false field. The default form widget for this field is a
CheckboxInput.
If you need to accept null values then use NullBooleanField
instead.
The default value of BooleanField is None when Field.default
isn’t defined
CharField A string field, for small- to large-sized strings. For large
amounts of text, use TextField. The default form widget for
this field is a TextInput. CharField has one extra required
argument: CharField.max_length

Ipsr.edu.in Django 22
DateField A date, represented in Python by a datetime.date instance
DateTimeField A date and time, represented in Python by a
datetime.datetime instance.
DecimalField A fixed-precision decimal number, represented in Python by
a Decimal instance. Has two required arguments -
DecimalField.max_digits, DecimalField.decimal_places. The
default form widget for this field is a NumberInput when
localize is False or TextInput otherwise
EmailField A CharField that checks that the value is a valid email
address. It uses EmailValidator to validate the input
FileField A file-upload field. FileField instances are created in your
database as varchar columns with a default max length of 100
characters
FloatField A floating-point number represented in Python by a float
instance.
The default form widget for this field is a NumberInput when
localize is False or TextInput otherwise
ImageField Inherits all attributes and methods from FileField, but also
validates that the uploaded object is a valid image
IntegerField An integer. Values from -2147483648 to 2147483647 are
safe in all databases supported by Django. The default form
widget for this field is a NumberInput when localize is False
or TextInput otherwise.
NullBooleanField Like a BooleanField, but allows NULL as one of the options.
Use this instead of a BooleanField with null=True. The
default form widget for this field is a NullBooleanSelect

Ipsr.edu.in Django 23
PositiveIntegerField Like an IntegerField, but must be either positive or zero (0).
Values from 0 to 2147483647
PositiveSmallIntegerField Values from 0 to 32767 are safe in all databases supported by
Django
SmallIntegerField Values from -32768 to 32767 are safe in all databases
supported by Django.
TextField A large text field. The default form widget for this field is a
Textarea
TimeField A time, represented in Python by a datetime.time instance.
The default form widget for this field is a TextInput
URLField A CharField for a URL
ForeignKey A many-to-one relationship. Requires two positional
arguments: the class to which the model is related and the
on_delete option.
ManyToManyField A many-to-many relationship. Requires a positional
argument: the class to which the model is related, which
works exactly the same as it does for ForeignKey
OneToOneField A one-to-one relationship

Installing the Model

We’ve written the code; now let’s create the tables in our database. In order
to do that, the first step is to activate these models in our Django project. We do
that by adding the ‘myapp’ 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

Ipsr.edu.in Django 24
python manage.py check

The check command runs the Django system check framework – a set of static
checks for validating Django projects. If all is well, you’ll see the message System
check identified no issues (0 silenced). 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. Any time you think you have problems with your
models, run python manage.py check. It tends to catch all the common model
problems.

If your models are valid, run the following command to tell Django that you have
made some changes to your models (in this case, you have made a new one):

python manage.py makemigrations myapp

Ipsr.edu.in Django 25
Migrations are how Django stores changes to your models (and thus your database
schema) – they’re just files on disk. In this instance, you will find a file names
0001_initial.py in the \migrations folder of the myapp app. The migrate command
will take your latest migration file and update your database schema automatically,
but first, let’s see what SQL that migration would run. The sqlmigrate command
takes migration names and returns their SQL:

python manage.py sqlmigrate myapp 0001

Table names are automatically generated by combining the name of the app
(myapp) and the lowercase name of the model (publisher, book, and author).

As we mentioned earlier, Django adds a primary key for each table automatically –
the id fields. You can override this. By convention, Django appends "_id" to the
foreign key field name. As you might have guessed, you can override this
behavior, too.The foreign key relationship is made explicit by a REFERENCES
statement.

Ipsr.edu.in Django 26
These CREATE TABLE statements are tailored to the database you’re using, so
database-specific field types such as auto_increment (MySQL), serial
(PostgreSQL), or integer primary key (SQLite) are handled for you automatically.
The same goes for quoting of column names (e.g., using double quotes or single
quotes

The sqlmigrate command doesn’t actually create the tables or otherwise touch your
database – it just prints output to the screen so you can see what SQL Django
would execute if you asked it. If you wanted to, you could copy and paste this SQL
into your database client, however Django provides an easier way of committing
the SQL to the database: the migrate command:

python manage.py migrate

The result will be

Once you’ve created a model, Django automatically provides a high-level Python


API for working with those models. Try it out by running

python manage.py shell from within your virtual environment and


typing the following:

Ipsr.edu.in Django 27
First, we import our Publisher model class. This lets us interact with the database
table that contains publishers.

We create a Publisher object by instantiating it with values for each field – name,
address, etc. To save the object to the database, call its save() method. Behind the
scenes, Django executes an SQL INSERT statement here.

To retrieve publishers from the database, use the attribute Publisher.objects, which
you can think of as a set of all publishers. Fetch a list of all Publisher objects in the
database with the statement Publisher.objects.all(). Behind the scenes, Django
executes an SQL SELECT statement here.

Ipsr.edu.in Django 28
One thing is worth mentioning, in case it wasn’t clear from this example. When
you’re creating objects using the Django model API, Django doesn’t save the
objects to the database until you call the save() method

Filtering Data

Naturally, it’s rare to want to select everything from a database at once; in most
cases, you’ll want to deal with a subset of your data. In the Django API, you can
filter your data using the filter() method:

>>> Publisher.objects.filter(name='Apress')

<QuerySet [<Publisher: Apress>]>

filter() takes keyword arguments that get translated into the appropriate SQL
WHERE clauses.

Django TEMPLATES

In the examples we have seen so far, the HTML was hard-coded directly in our
Python code. Although this technique was convenient for the purpose of explaining
how views work, it’s not a good idea to hard-code HTML directly into your views.
Here’s why:

 Any change to the design of the page requires a change to the Python code.
The design of a site tends to change far more frequently than the underlying
Python code, so it would be convenient if the design could change without
needing to modify the Python code.
 A common webpage template has hundreds of lines of HTML and scripts.
Untangling and troubleshooting program code from this mess is a nightmare

Ipsr.edu.in Django 29
 Writing Python code and designing HTML are two different disciplines, and
most professional web development environments split these responsibilities
between separate people (or even separate departments). Designers and
HTML/CSS coders shouldn’t be required to edit Python code to get their job
done.
 It’s most efficient if programmers can work on Python code and designers
can work on templates at the same time, rather than one person waiting for
the other to finish editing a single file that contains both Python and HTML.

For these reasons, it’s much cleaner and more maintainable to separate the design
of the page from the Python code itself. We can do this with Django’s 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 (template tags) that regulate how the document should be displayed. Usually,
templates are used for producing HTML, but Django templates are equally capable
of generating any text-based format.

A Django project can be configured with one or several template engines (or even
zero if you don’t use templates).

Django Template Language

Django ships with a built-in backend for its own template system – the Django
Template Language (DTL).

A template contains variables, which get replaced with values when the template
is evaluated, and tags, which control the logic of the template.

Ipsr.edu.in Django 30
Example

This Django template describes an HTML page that thanks a person for placing an
order with a company. Think of it as a form letter:

Variables

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

Variable names consist of any combination of alphanumeric characters and the


underscore ("_").Use a dot (.) to access attributes of a variable. For eg:
{{section.title}}

Ipsr.edu.in Django 31
If you use a variable that doesn’t exist, the template system will insert the value of
the string_if_invalid option, which is set to '' (the empty string) by default.

Filters

We can modify variables for display by using filters. The normal form is
{{variable | filter}}. If the filters are chained, the output of one filter is applied to
next. Some filters take arguments. A filter argument looks like this: {{
bio|truncatewords:30 }}. This will display the first 30 words of the bio variable.
Filter arguments that contain spaces must be quoted; for example, to join a list with
commas and spaces you’d use {{ list|join:", " }}.

Django provides about sixty built-in template filters. Here are some of them:

https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#ref-templates-
builtins-filters

1. default
If a variable is false or empty, use given default. Otherwise, use the value of
the variable.
eg: {{ value | default:"nothing" }}

2. length
Returns the length of the value. This works for both strings and lists.
eg: {{value | length}} returns 4 if value is [‘a’,’b’,’c’,’d’]

3. filesizeformat
Formats the value like a “human-readable” file size (i.e. '13 KB', '4.1 MB',
'102 bytes', etc.). For example:
{{ value|filesizeformat }}

Ipsr.edu.in Django 32
If value is 123456789, the output would be 117.7 MB.

Tags

Tags look like this: {% tag %}. Tags are more complex than variables: Some
create text in the output, some control flow by performing loops or logic, and some
load external information into the template to be used by later variables. Some tags
require beginning and ending tags (i.e. {% tag %} ... tag contents ... {% endtag
%}). Django ships with about two dozen built-in template tags.

for

Loop over each item in an array. For example, to display a list of athletes provided
in athlete_list.

if, elif, and else

Evaluates a variable, and if that variable is “true” the contents of the block are
displayed.

Ipsr.edu.in Django 33
Single line comment

To comment-out part of a line in a template, use the comment syntax: {# #}.

For example, this template would render as 'hello':

{# greeting #}hello

A comment can contain any template code, invalid or not.

Multi line comment

<% comment %> …. <%endcomment%> is used to write multiline comments. An


optional note may be inserted in the first tag. For example, this is useful when
commenting out code for documenting why the code was disabled.

include

Loads a template and renders it with the current context. This is a way of
“including” other templates within a template. The template name can either be a
variable or a hard-coded (quoted) string, in either single or double quotes.

or

An included template is rendered within the context of the template that includes it.

The name_snippet.html template:

Ipsr.edu.in Django 34
You can pass additional context to the template using keyword arguments:

Components

Engine

django.template.Engine encapsulates an instance of the Django template system.


The main reason for instantiating an Engine directly is to use the Django template
language outside of a Django project.

django.template.backends.django.DjangoTemplates is a thin wrapper adapting


django.template.Engine to Django’s template backend API.

Template

django.template.Template represents a compiled template. Templates are obtained


with Engine.get_template() or Engine.from_string()

Likewise django.template.backends.django.Template is a thin wrapper adapting


django.template.Template to the common template API.

Context

django.template.Context holds some metadata in addition to the context data. It is


passed to Template.render() for rendering a template.

django.template.RequestContext is a subclass of Context that stores the current


HttpRequest and runs template context processors.

Ipsr.edu.in Django 35
The common API doesn’t have an equivalent concept. Context data is passed in a
plain dict and the current HttpRequest is passed separately if needed.

Loaders

Template loaders are responsible for locating templates, loading them, and
returning Template objects. Django provides several built-in template loaders and
supports custom template loaders.

Context processors

Context processors are functions that receive the current HttpRequest as an


argument and return a dict of data to be added to the rendering context. Their main
use is to add common data shared by all templates to the context without repeating
code in every view. Django provides many built-in context processors.

Configuration

Templates engines are configured with the TEMPLATES setting. It’s a list of
configurations, one for each engine. The default value is empty. The settings.py
generated by the startproject command defines a more useful value:

First create a directory templates in project directory and inside this directory
create another directory for specific app.(In our case myapp). Then configure
template object in settings.py

Ipsr.edu.in Django 36
For static files like css or images we need to create another directory static inside
project folder and add this directory configuration in settings.py as follows

Display dynamic data using templates.

Now we can create a template for showing the current date and time

For that create a file named index.html in myapp directory inside templates
directory as follows.

Ipsr.edu.in Django 37
Load staticfiles is used to load files from static folders

To apply css create a style.css file inside css directory inside static directory.

Render template from view

To render template from view add a new function inside view as done earlier

Ipsr.edu.in Django 38
Configure urlconfig for home function and run using the url

http://127.0.0.1:8000/myapp/home/

Django WITH Mysql

For connecting to mysql from django first we need to configure the database in
settings.py .

Create a database named django_mydb in mysql then

We can use the same model used for sqlite db. Follow the steps described in
django model tutorial.

Ipsr.edu.in Django 39
This will create tables in mysql database.

Some default tables will also created which is used by django admin.

Ipsr.edu.in Django 40
Display data from mysql tables in django view using model and templates

For display data from database first we need to create a view to get data from
model and render the data in html. Create an html file in template folder of our
app. Here is an example to display all authors from table author.

Fig:index.html

Then create a function inside view to render the html along with model data as
follows

Ipsr.edu.in Django 41
Author.objects.all() function will return all Authors data as Author object list.

Run the server and you will get the following result

Django FORM HANDLING .

Now we can create a simple form example to add authors in the


database.Create a html form in template and render it using view.

Ipsr.edu.in Django 42
In the template, there is a {% csrf_token %} template tag inside each POST form
that targets an internal URL.

If you are not using CsrfViewMiddleware, then you must use csrf_protect on any
views that use the csrf_token template tag, as well as those that accept the POST
data.

The form has a valid CSRF token. After logging in another browser tab or hitting
the back button after a login, you may need to reload the page with the form,
because the token is rotated after a login.

And inside view create authoradd function to accept form data and save the data in
database using object save method.

Ipsr.edu.in Django 43
This will save the data in database and will display authors list with newly added
author data

Ipsr.edu.in Django 44

You might also like