Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction
Django is a Python-based free and open-source web framework, which follows the model-view-template
architectural pattern. It is maintained by the Django Software Foundation, an independent organization
established as a 501 non-profit. Django's primary goal is to ease the creation of complex, database-driven
websites.
Django is a web application framework written in Python programming language. It is based on MVT
(Model View Template) design pattern. The Django is very demanding due to its rapid development
feature. It takes less time to build application after collecting client requirement.
This framework uses a famous tag line:The web framework for perfectionists with deadlines.
By using Django, we can build web applications in very less time. Django is designed in such a manner
that it handles much of configure things automatically, so we can focus on application development only.
History
Django was design and developed by Lawrence journal worldin2003 and publicly released under BSD
license (free software license with minimal restriction) in July 2005. Currently, DSF (Django Software
Foundation) maintains its development and release cycle.
Django was released on 21, July 2005. Its current stable version is 2.0.3 which was released on 6 March,
2018.
Advantages of Django
Here are few advantages of using Django which can be listed out here −
Object-Relational Mapping (ORM) Support − Django provides a bridge between the data model
and the database engine, and supports a large set of database systems including MySQL, Oracle,
Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only
NoSQL databases supported are MongoDB and google app engine.
Administration GUI − Django provides a nice ready-to-use user interface for administrative
activities.
Django MVT
https://www.javatpoint.com/django-model
The MVT (Model View Template) is a software design pattern. It is a collection of three important
components Model View and Template. The Model helps to handle database. It is a data access layer
which handles the data.
The Templateis a presentation layer which handles User Interface part completely.
The View is used to execute the business logic and interact with a model to carry data and renders a
template.
Although Django follows MVC pattern but maintains its own conventions. So, control is handled by the
framework itself.
There is no separate controller and complete application is based on Model View and Template. That’s
why it is called MVT application.
See the following graph that shows the MVT based control flow.
]]]]]]]]]]]]]]]]]
Here, a user requests for a resource to the Django, Django works as a controller and check to the
available resource in URL.
If URL maps, a view is called that interact with model and template, it renders a template.
Django Model is a subclass of django.db.models.Model and each field of the model class represents a
database field (column).
Django provides us a database-abstraction API which allows us to create, retrieve, update and delete a
record from the mapped table.
Model is defined in Models.py file. This file can contain multiple models.
Let's see an example here, we are creating a model Employee which has two
fields first_name and last_name.
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
The first_name and last_name fields are specified as class attributes and each attribute maps to a
database column.
This model will create a table into the database that looks like below.
The created table contains an auto-created id field. The name of the table is a combination of app name
and model name that can be changed further.
Register / Use Model
After creating a model, register model into the INSTALLED_APPS
inside settings.py.
For example,
INSTALLED_APPS = [
#...
'appname',
#...
]
After creating your model, you will need Django to generate the actual database −
BooleanField class BooleanField(**options) A true/false field. The default form widget for this
field is a CheckboxInput.
EmailField class EmailField(max_length=254, It is a CharField that checks that the value is a valid
**options) email address.
ImageField class ImageField(upload_to=None, It inherits all attributes and methods from FileField,
height_field=None, but also validates that the uploaded object is a valid
width_field=None, image.
max_length=100, **options)
NullBooleanField class NullBooleanField(**options) Like a BooleanField, but allows NULL as one of the
options.
PositiveIntegerField class Like an IntegerField, but must be either positive or
PositiveIntegerField(**options) zero (0). Values from 0 to 2147483647 are safe in all
databases supported by Django.
SmallIntegerField class SmallIntegerField(**options) It is like an IntegerField, but only allows values under
a certain (database-dependent) point.
TextField class TextField(**options) A large text field. The default form widget for this
field is a Textarea.
Field Options
Each field requires some arguments that are used to set column attributes. For example, CharField
requires mac_length to specify varchar database.
Field Particulars
Options
Choices An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.
Default The default value for the field. This can be a value or a callable object [[[object that can
be called like a function]]]]
help_text Extra "help" text to be displayed with the form widget. It's useful for documentation even
if your field isn't used on a form.
We created a model Student that contains the following code in models.py file.
//models.py
1. class Student(models.Model):
2. first_name = models.CharField(max_length=20)
3. last_name = models.CharField(max_length=30)
4. contact = models.IntegerField()
5. email = models.EmailField(max_length=50)
6. age = models.IntegerField()
It will create a table myapp_student. The table structure looks like the below.
—————————————————-
Django Views
A view is a place where we put our business logic of the application. The view is a python
function which is used to perform some business logic and return a response to the user. This
response can be the HTML contents of a Web page, or a redirect, or a 404 error.
All the view function are created inside the views.py file of the Django app.
//views.py
1. import datetime # datetime is a library that has method to get current date & time
2. # Create your views here.
3. from django.http import HttpResponse
4. def index(request): # view function that takes HTTP request and respond back
5. now = datetime.datetime.now()
6. html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
7. return HttpResponse(html) # rendering the template in HttpResponse
First, we will import DateTime library that provides a method to get current date and time and
HttpResponse class.
Next, we define a view function index that takes HTTP request and respond back.
View calls when gets mapped with URL in urls.py. For example
1. path('index/', views.index),
Output:
Returning Errors
Django provides various built-in error classes that are the subclass of HttpResponse and use to show error message
as HTTP response. Some classes are listed below.
Class Description
class It is used to designate that a page hasn't been modified since the user's last
HttpResponseNotModifie request (status code 304).
d
class It acts just like HttpResponse but uses a 400 status code.
HttpResponseBadRequest
class It acts just like HttpResponse but uses a 404 status code.
HttpResponseNotFound
class It acts just like HttpResponse but uses a 410 status code.
HttpResponseNotAllowed
HttpResponseServerError It acts just like HttpResponse but uses a 500 status code.
// views.py
Output:
Django View HTTP Decorators
HTTP Decorators are used to restrict access to view based on the request method.
Syntax
require_http_methods(request_method_list)
This method will execute only if the request is an HTTP GET request.
//urls.py
Output:
————————————————————————————————————————————-
Django Templates
Django provides a convenient way to generate dynamic HTML pages by using its template system.
A template consists of static parts of the desired HTML output as well as some special syntax describing how
dynamiccontent will be inserted.
Django template engine is used to separate the design from the python code and allows us to build dynamic web
pages.
1. TEMPLATES = [
2. {
3. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
4. 'DIRS': [os.path.join(BASE_DIR,'templates')],
5. 'APP_DIRS': True,
6. 'OPTIONS': {
7. 'context_processors': [
8. 'django.template.context_processors.debug',
9. 'django.template.context_processors.request',
10. 'django.contrib.auth.context_processors.auth',
11. 'django.contrib.messages.context_processors.messages',
12. ],
13. },
14. },
15. ]
Here, we mentioned that our template directory name is templates. By default, DjangoTemplates looks for
a templates subdirectory in each of the INSTALLED_APPS.
// index.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Index</title>
6. </head>
7. <body>
8. <h2>Welcome to Django!!!</h2>
9. </body>
10. </html>
Loading Template
To load the template, call get_template() method as we did below and pass template name.
//views.py
//urls.py
1. path('index/', views.index),
1. INSTALLED_APPS = [
2. 'django.contrib.admin',
3. 'django.contrib.auth',
4. 'django.contrib.contenttypes',
5. 'django.contrib.sessions',
6. 'django.contrib.messages',
7. 'django.contrib.staticfiles',
8. 'myapp'
9. ]
Run Server
Execute the following command and access the template by entering localhost:8000/index at the browser.
Variables
Variables associated with a context can be accessed by {{}} (double curly braces). For example, a
variable name value is rahul. Then the following statement will replace name with its value.
1. My name is {{name}}.
2. My name is rahul
//views.py
//index.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Index</title>
6. </head>
7. <body>
8. <h2>Welcome to Django!!!</h2>
9. <h3>My Name is: {{ student }}</h3>
10. </body>
11. </html>
Output:
Tags
In a template, Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a
control structure e.g. an "if" statement or a "for" loop, grab content from a database etc.
1. {% csrf_token %}
2.
3. {% if user.is_authenticated %}
4. Hello, {{ user.username }}.
5. {% endif %}
==================================================
Django Forms
Django provides a Form class which is used to create HTML forms. It describes a form and how it works
and appears.
It is similar to the ModelForm class that creates a form by using the Model, but it does not require the
Model.
Each field of the form class map to the HTML form <input> element and each one is a class itself, it
manages form data and performs validation while submitting the form.
A StudentForm is created that contains two fields of CharField type. Charfield is a class and used to
create an HTML text input component in the form.
The label is used to set HTML label of the component and max_length sets length of an input value.
Note: Django Form does not include <form> tags, or a submit button. We'll have to provide those
ourselves in the template.
Commonly used fields and their details are given in the below table.
Let's see a complete example to create an HTML form with the help of Django Form class.
// views.py
Passing the context of form into index template that looks like this:
// index.html
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>Index</title>
6. </head>
7. <body>
8. <form method="POST" class="post-form">
9. {% csrf_token %}
10. {{ form.as_p }}
11. <button type="submit" class="save btn btn-default">Save</button>
12. </form>
13. </body>
14. </html>
Run Server and access the form at browser by localhost:8000/index, and it will produce the following
output.
There are other output options though for the <label>/<input> pairs:
=========================================================
This is a built-in module and designed to perform admin related tasks to the user.
Let's see how to activate and use Django's admin module (interface).
The admin app (django.contrib.admin) is enabled by default and already added into
INSTALLED_APPS section of the settings file.
To access it at browser use '/admin/' at a local machine like localhost:8000/admin/ and it shows the
following output:
It prompts for login credentials if no password is created yet, use the following command to create a user.
It is a Django Admin Dashboard. Here, we can add and update the registered models. The model
registration process will be discussed in further chapters.
==================================
Security in Django¶(page 508 of django pdf)
This document is an overview of Django’s security features. It includes advice on securing a Django-
powered site.
Using Django templates protects you against the majority of XSS attacks. However, it is important to
understand what protections it provides and its limitations.
You should also be very careful when storing HTML in the database, especially when that HTML is
retrieved and displayed.
CSRF attacks allow a malicious user to execute actions using the credentials of another user without
that user’s knowledge or consent.
Django has built-in protection against most types of CSRF attacks, providing you have enabled and used
it where appropriate. However, as with any mitigation technique, there are limitations. For example, it is
possible to disable the CSRF module globally or for particular views. You should only do this if you
know what you are doing. There are other limitations if your site has subdomains that are outside of your
control.
CSRF protection works by checking for a secret in each POST request. This ensures that a malicious user
cannot simply “replay” a form POST to your website and have another logged in user unwittingly submit
that form. The malicious user would have to know the secret, which is user specific (using a cookie).
Django’s querysets are protected from SQL injection since their queries are constructed using
query parameterization. A query’s SQL code is defined separately from the query’s parameters. Since
parameters may be user-provided and therefore unsafe, they are escaped by the underlying database
driver.
Django also gives developers power to write raw queries or execute custom sql. These capabilities should
be used sparingly and you should always be careful to properly escape any parameters that the user can
control. In addition, you should exercise caution when using extra() and RawSQL.
[[[[[[ A character escape is a way of representing a character in source code using only ASCII
characters. In HTML you can escapethe following ways.
]]]]]]
Clickjacking protection¶
Clickjacking is a type of attack where a malicious site wraps another site in a frame. This attack
can result in an unsuspecting user being tricked into performing unintended actions on the target site.
Django contains clickjacking protection in the form of the X-Frame-Options middleware which in a
supporting browser can prevent a site from being rendered inside a frame. It is possible to disable the
protection on a per view basis or to configure the exact header value sent.
The middleware is strongly recommended for any site that does not need to have its pages wrapped in a
frame by third party sites, or only needs to allow that for a small section of the site.
SSL/HTTPS¶
It is always better for security to deploy your site behind HTTPS. Without this, it is possible for malicious
network users to sniff authentication credentials or any other information transferred between client and
server, and in some cases – active network attackers – to alter data that is sent in either direction.
If you want the protection that HTTPS provides, and have enabled it on your server, there are some
additional steps you may need:
Set SECURE_SSL_REDIRECT to True, so that requests over HTTP are redirected to HTTPS.
Please note the caveats under SECURE_PROXY_SSL_HEADER. For the case of a reverse
proxy, it may be easier or more secure to configure the main Web server to do the redirect to
HTTPS.
If a browser connects initially via HTTP, which is the default for most browsers, it is possible for
existing cookies to be leaked. For this reason, you should set
your SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE settings to True. This
instructs the browser to only send these cookies over HTTPS connections. Note that this will
mean that sessions will not work over HTTP, and the CSRF protection will prevent any POST
data being accepted over HTTP (which will be fine if you are redirecting all HTTP traffic to
HTTPS).
Because even seemingly-secure web server configurations are susceptible to fake Host headers, Django
validates Hostheaders against the ALLOWED_HOSTS setting in
he django.http.HttpRequest.get_host() method.
Additionally, Django requires you to explicitly enable support for the X-Forwarded-Host header (via
theUSE_X_FORWARDED_HOST setting) if your configuration requires it.
Session security¶
Similar to the CSRF limitations requiring a site to be deployed such that untrusted users don’t have access
to any subdomains, django.contrib.sessions also has limitations. See the session topic guide section on
security for details.
User-uploaded content¶
Note
Consider serving static files from a cloud service or CDN to avoid some of these issues.
If your site accepts file uploads, it is strongly advised that you limit these uploads in your Web
server configuration to a reasonable size in order to prevent denial of service (DOS) attacks. In
Apache, this can be easily set using theLimitRequestBody directive.
If you are serving your own static files, be sure that handlers like Apache’s mod_php, which
would execute static files as code, are disabled. You don’t want users to be able to execute
arbitrary code by uploading and requesting a specially crafted file.
Django’s media upload handling poses some vulnerabilities when that media is served in ways
that do not follow security best practices. Specifically, an HTML file can be uploaded as an
image if that file contains a valid PNG header followed by malicious HTML. This file will pass
verification of the library that Django uses for ImageField image processing (Pillow). When this
file is subsequently displayed to a user, it may be displayed as HTML depending on the type and
configuration of your web server.
No bulletproof technical solution exists at the framework level to safely validate all user uploaded
file content, however, there are some other steps you can take to mitigate these attacks:
1. One class of attacks can be prevented by always serving user uploaded content from a
distinct top-level or second-level domain. This prevents any exploit blocked by same-
origin policy protections such as cross site scripting. For example, if your site runs
on example.com, you would want to serve uploaded content (the MEDIA_URL setting)
from something like usercontent-example.com. It’s not sufficient to serve content from
a subdomain like usercontent.example.com.
2. Beyond this, applications may choose to define a whitelist of allowable file extensions for
user uploaded files and configure the web server to only serve such files.
Make sure that your Python code is outside of the Web server’s root. This will ensure that your
Python code is not accidentally served as plain text (or accidentally executed).
Take care with any user uploaded files.
Django does not throttle requests to authenticate users. To protect against brute-force attacks
against the authentication system, you may consider deploying a Django plugin or Web server
module to throttle these requests.
Keep your SECRET_KEY a secret.
It is a good idea to limit the accessibility of your caching system and database using a firewall.
Take a look at the Open Web Application Security Project (OWASP) Top 10 list which identifies
some common vulnerabilities in web applications. While Django has tools to address some of the
issues, other issues must be accounted for in the design of your project.
Django has full support for translation of text, formatting of dates, times and numbers, and time zones.
It allows developers and template authors to specify which parts of their apps should be translated
or formatted for local languages and cultures.
It uses these hooks to localize Web apps for particular users according to their preferences.
Obviously, translation depends on the target language, and formatting usually depends on the target
country. This information is provided by browsers in the Accept-Language header. However, the time
zone isn’t readily available.
Definitions¶
The words “internationalization” and “localization” often cause confusion; here’s a simplified definition:
internationalization
localization
Writing the translations and local formats. Usually done by translators.
More details can be found in the W3C Web Internationalization FAQ, the Wikipedia article or the GNU
gettext documentation.
Here are some other terms that will help us to handle a common language:
locale name
A locale name, either a language specification of the form ll or a combined language and country
specification of the formll_CC. Examples: it, de_AT, es, pt_BR. The language part is always in
lower case and the country part in upper case. The separator is an underscore.
language code
Represents the name of a language. Browsers send the names of the languages they accept in
the Accept-Language HTTP header using this format. Examples: it, de-at, es, pt-br. Language
codes are generally represented in lower-case, but the HTTP Accept-Language header is case-
insensitive. The separator is a dash.
message file
A message file is a plain-text file, representing a single language, that contains all
available translation strings and how they should be represented in the given language. Message
files have a .po file extension.
translation string
A literal that can be translated.
format file
A format file is a Python module that defines the data formats for a given locale.
=======================================================================
https://djangopackages.org/grids/g/this-site/
Data Tools
Apps, packages, and modules related to data management: import/export, fixtures, serialization and
formats, handling large QuerySets, etc.
Developer Tools
Django has developer tools for debugging, logging, and getting work done.
Packages ›› django-debug-toolbar
SENTRY Sentry is cross-platform application monitoring, with a focus
on error reporting.
django-debug-toolbar A configurable set of panels that display various
debug information about the current
request/response.
Geographic Frame
GeoDjango is a geographic sub-framework of Django that allows developers to build GIS-based and
location aware web applications.
Before, you can start using Django and GeoDjango, you'll need a few prerequisites. On your
development machine, you need to have:
Introducing GeoDjango
GeoDjango stands for Geographic Django and it's a framework that makes part of Django and
can be used for creating applications which make use of geospatial or geographic data. These
applications can be either full-fledged GIS (Geographic Information System) systems or simple
web location based applications.
The great thing about GeoDjango is its tight integration with the Django ORM which allows you
to manipulate spatial data in geospatial databases like PostGIS, Oracle or MySQL or any other
database from high level API that abstracts the differences between the different
implementations and also the complexities related to spatial queries.
You can use GeoDjango to make queries that find the distances between two locations on earth
and the areas of objects among other things.
GeoDjango requires a spatial database and the following libraries installed on your system:
GEOS that stands for Geometry Engine Open Source and implements the OCG Simple
Feature for SQL specification.
GDAL that stands for Geospatial Data Abstraction Library. It’s an open-source library
that abstracts working with GIS data formats.
PROJ.4 that stands for Cartographic Projections library and implements the required
APIs for working with spatial reference systems and projections.
Introducing GeoDjango
GeoDjango stands for Geographic Django and it's a framework that makes part of Django and
can be used for creating applications which make use of geospatial or geographic data. These
applications can be either full-fledged GIS (Geographic Information System) systems or simple
web location based applications.
The great thing about GeoDjango is its tight integration with the Django ORM which allows you
to manipulate spatial data in geospatial databases like PostGIS, Oracle or MySQL or any other
database from high level API that abstracts the differences between the different
implementations and also the complexities related to spatial queries.
You can use GeoDjango to make queries that find the distances between two locations on earth
and the areas of objects among other things.
GeoDjango requires a spatial database and the following libraries installed on your system:
GEOS that stands for Geometry Engine Open Source and implements the OCG Simple
Feature for SQL specification.
GDAL that stands for Geospatial Data Abstraction Library. It’s an open-source library
that abstracts working with GIS data formats.
PROJ.4 that stands for Cartographic Projections library and implements the required
APIs for working with spatial reference systems and projections.
GeoDjango requires the open source GDAL, GEOS and PROJ.4 libraries for working with
spatial databases, spatial reference systems, GIS data formats and performs mathematical
operations related to geography and locations.
Install PostgreSQL
In your terminal, run the following command to install PostgreSQL in your system if it's not
already installed:
You also need to install the psycopg2 PostgreSQL adapter for Python using pip
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'YOUR_POSTGIS_DATABASE_NAME',
'USER': 'YOUR_DATABASE_USER_NAME',
'PASSWORD': 'YOUR_DATABASE_USER_PASSWORD',
'HOST': 'localhost',
'PORT': '5432'
}
}
Open the settings.py file and add the 'django.contrib.gis' module to the INSTALLED_APPS array:
INSTALLED_APPS = [
# [...]
'django.contrib.gis'
]
DJANGO an overview
Draw any one of the diagram either the above simple diagram or the complete below one.
IF a genral question about django comes you can write this overview