Sei sulla pagina 1di 38

UNIT V DJANGO

Introduction to Django-Django model layer – View layer – Template Layer – Forms –


Automated admin interface – Django Security – Internationalization and localization – Django
Web application tools – Core functionalities – Geographic Frame

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.

 Multilingual Support − Django supports multilingual websites through its built-in


internationalization system. So you can develop your website, which would support multiple
languages.
 Framework Support − Django has built-in support for Ajax, RSS, Caching and various other
frameworks.

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

[[[[[[[[ MVC Pattern

]]]]]]]]]]]]]]]]]
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 responds back to the user andsends a template as a response.


Django Model
In Django, a model is a class which is used to contain essential fields and methods. Each model class
maps to a single table in the database.

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.

from django.db import models

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.

CREATE TABLE appname_employee (


"id" INT NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);

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 −

$python manage.py syncdb

Django Model Fields


The fields defined inside the Model class are the columns name of the mapped table. The fields name
should not be python reserve words like clean, save or delete etc.

Django provides various built-in fields types.


Field Name Class Particular

AutoField class AutoField(**options) It An IntegerField that automatically increments.

BigAutoField class BigAutoField(**options) It is a 64-bit integer, much like an AutoField except


that it is guaranteed to fit numbers from 1 to
9223372036854775807.

BigIntegerField class BigIntegerField(**options) It is a 64-bit integer, much like an IntegerField except


that it is guaranteed to fit numbers from -
9223372036854775808 to 9223372036854775807.

BinaryField class BinaryField(**options) A field to store raw binary data.

BooleanField class BooleanField(**options) A true/false field. The default form widget for this
field is a CheckboxInput.

CharField class DateField(auto_now=False, It is a date, represented in Python by a datetime.date


auto_now_add=False, **options) instance.

DateTimeField class It is a date, represented in Python by a datetime.date


DateTimeField(auto_now=False, instance.
auto_now_add=False, **options)

DateTimeField class It is used for date and time, represented in Python by


DateTimeField(auto_now=False, a datetime.datetime instance.
auto_now_add=False, **options)

DecimalField class It is a fixed-precision decimal number, represented in


DecimalField(max_digits=None, Python by a Decimal instance.
decimal_places=None, **options)

DurationField class DurationField(**options) A field for storing periods of time.

EmailField class EmailField(max_length=254, It is a CharField that checks that the value is a valid
**options) email address.

FileField class FileField(upload_to=None, It is a file-upload field.


max_length=100, **options)

FloatField class FloatField(**options) It is a floating-point number represented in Python by


a float instance.

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)

IntegerField class IntegerField(**options) It is an integer field. Values from -2147483648 to


2147483647 are safe in all databases supported by
Django.

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.

TimeField class TimeField(auto_now=False, A time, represented in Python by a datetime.time


auto_now_add=False, **options) instance.

Django Model Fields Example

1. first_name = models.CharField(max_length=50) # for creating varchar column


2. release_date = models.DateField() # for creating date column
3. num_stars = models.IntegerField() # for creating integer column

Field Options
Each field requires some arguments that are used to set column attributes. For example, CharField
requires mac_length to specify varchar database.

Common arguments available to all field types. All are optional.

Field Particulars
Options

Null Django will store empty values as NULL in the database.

Blank It is used to allowed field to be blank.

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.

primary_key This field is the primary key for the model.


Unique This field must be unique throughout the table.

Django Model Example

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()

After that apply migration by using the following command.

1. python3 manage.py makemigrations myapp

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.

Django View Simple Example

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

Let's step through the code.

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.

Django View Example

// views.py

1. from django.shortcuts import render


2. # Create your views here.
3. from django.http import HttpResponse, HttpResponseNotFound
4. def index(request):
5. a=1
6. if a:
7. return HttpResponseNotFound('<h1>Page not found</h1>')
8. else:
9. return HttpResponse('<h1>Page was found</h1>') # rendering the template in HttpRespons
e

Output:
Django View HTTP Decorators
HTTP Decorators are used to restrict access to view based on the request method.

These decorators are listed in django.views.decorators.http and return a


django.http.HttpResponseNotAllowed if the conditions are not met.

Syntax

require_http_methods(request_method_list)

Django Http Decorator Example


//views.py

1. from django.shortcuts import render


2. # Create your views here.
3. from django.http import HttpResponse, HttpResponseNotFound
4. from django.views.decorators.http import require_http_methods
5. @require_http_methods(["GET"])
6. def show(request):
7. return HttpResponse('<h1>This is Http GET request.</h1>')

This method will execute only if the request is an HTTP GET request.

//urls.py

1. from django.contrib import admin


2. from django.urls import path
3. from myapp import views
4. urlpatterns = [
5. path('admin/', admin.site.urls),
6. path('index/', views.index),
7. path('show/', views.show),
8. ]

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.

Why Django Template?


In HTML file, we can't write python code because the code is only interpreted by python interpreter not the browser.
We know that HTML is a static markup language, while Python is a dynamic programming language.

Django template engine is used to separate the design from the python code and allows us to build dynamic web
pages.

Django Template Configuration


To configure the template system, we have to provide some entries in settings.py file.

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.

Django Template Simple Example


First, create a directory templates inside the project app as we did below.
After that create a template index.html inside the created folder.
Our template index.html contains the following code.

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

1. from django.shortcuts import render


2. #importing loading from django template
3. from django.template import loader
4. # Create your views here.
5. from django.http import HttpResponse
6. def index(request):
7. template = loader.get_template('index.html') # getting our template
8. return HttpResponse(template.render()) # rendering the template in HttpResponse

Set a URL to access the template from the browser.

//urls.py

1. path('index/', views.index),

Register app inside the INSTALLED_APPS

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.

1. $ python3 manage.py runserver

Django Template Language


Django template uses its own syntax to deal with variable, tags, expressions etc. A template is rendered
with a context which is used to get value at a web page. See the examples.

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

Django Variable Example

//views.py

1. from django.shortcuts import render


2. #importing loading from django template
3. from django.template import loader
4. # Create your views here.
5. from django.http import HttpResponse
6. def index(request):
7. template = loader.get_template('index.html') # getting our template
8. name = {
9. 'student':'rahul'
10. }
11. return HttpResponse(template.render(name)) # rendering the template in HttpResponse

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

Tags are surrounded by {% %} braces. For example.

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.

Lets see an example, in which we are creating some fields too.

1. from django import forms


2. class StudentForm(forms.Form):
3. firstname = forms.CharField(label="Enter first name",max_length=50)
4. lastname = forms.CharField(label="Enter last name", max_length = 100)

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.

When rendered, it produces the following HTML to the browser.

1. <label for="id_firstname">Enter first name:</label>


2. <input type="text" name="firstname" required maxlength="50" id="id_firstname" />
3. <label for="id_lastname">Enter last name:</label> <input type="text" name="lastname" required
maxlength="100" id="id_lastname" />

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.

Name Class HTML Empty value


Input

BooleanField class CheckboxInput False


BooleanField(**kwargs)

CharField class CharField(**kwargs) TextInput Whatever you've given as


empty_value.
ChoiceField class Select '' (an empty string)
ChoiceField(**kwargs)

DateField class DateField(**kwargs) DateInput None

DateTimeField class DateTimeInput None


DateTimeField(**kwargs)

DecimalField class NumberInput None


DecimalField(**kwargs)

EmailField class EmailField(**kwargs) EmailInput '' (an empty string)

FileField class FileField(**kwargs) ClearableFileInput None

ImageField class ImageField(**kwargs) ClearableFileInput None

Let's see a complete example to create an HTML form with the help of Django Form class.

Building a Form in Django


Suppose we want to create a form to get Student information, use the following code.

1. from django import forms


2. class StudentForm(forms.Form):
3. firstname = forms.CharField(label="Enter first name",max_length=50)
4. lastname = forms.CharField(label="Enter last name", max_length = 100)

Put this code into the forms.py file.

Instantiating Form in Django


Now, we need to instantiate the form in views.py file. See, the below code.

// views.py

1. from django.shortcuts import render


2. from myapp.form import StudentForm
3.
4. def index(request):
5. student = StudentForm()
6. return render(request,"index.html",{'form':student})

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>

Provide the URL in urls.py

1. from django.contrib import admin


2. from django.urls import path
3. from myapp import views
4. urlpatterns = [
5. path('admin/', admin.site.urls),
6. path('index/', views.index),
7. ]

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:

 {{ form.as_table }} will render them as table cells wrapped in <tr> tags


 {{ form.as_p }} will render them wrapped in <p> tags
 {{ form.as_ul }} will render them wrapped in <li> tags
Note: that we'll have to provide the surrounding <table> or <ul> elements yourself.

=========================================================

Django Admin Interface


Django provides a built-in admin module which can be used to perform CRUD operations on the models.
It reads metadata from the model to provide a quick interface where the user can manage the content of
the application.

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.

Create an Admin User


1. $ python3 managen.py createsuperuser
Now start development server and access admin login.

1. $ python3 manage.py runserver

Provide created username and password and login.

After login successfully, it shows the following interface.

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.

Cross site scripting (XSS) protection¶


XSS attacks allow a user to inject client side scripts into the browsers of other users. This is usually
achieved by storing the malicious scripts in the database where it will be retrieved and displayed to
other users, or by getting users to click a link which will cause the attacker’s JavaScript to be executed
by the user’s browser. However, XSS attacks can originate from any untrusted source of data, such as
cookies or Web services, whenever the data is not sufficiently sanitized before including in a page.

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.

Cross site request forgery (CSRF) protection¶

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

SQL injection protection¶


SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a
database. This can result in records being deleted or data leakage.

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.

& becomes &amp;


< becomes &lt;
> becomes &gt;

]]]]]]

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:

 If necessary, set SECURE_PROXY_SSL_HEADER, ensuring that you have understood the


warnings there thoroughly. Failure to do this can result in CSRF vulnerabilities, and failure to do
it correctly can also be dangerous!

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

 Use ‘secure’ cookies.

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

 Use HTTP Strict Transport Security (HSTS)


HSTS is an HTTP header that informs a browser that all future connections to a particular site
should always use HTTPS. Combined with redirecting requests over HTTP to HTTPS, this will
ensure that connections always enjoy the added security of SSL provided one successful
connection has occurred. HSTS may either be configured
withSECURE_HSTS_SECONDS, SECURE_HSTS_INCLUDE_SUBDOMAINS,
and SECURE_HSTS_PRELOAD, or on the Web server.

Host header validation¶


Django uses the Host header provided by the client to construct URLs in certain cases. While these values
are sanitized to prevent Cross Site Scripting attacks, a fake Host value can be used for Cross-Site Request
Forgery, cache poisoning attacks, and poisoning links in emails.

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.

Additional security topics¶


While Django provides good security protection out of the box, it is still important to properly deploy your
application and take advantage of the security protection of the Web server, operating system and other
components.

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

Internationalization and localization¶


Overview¶
The goal of internationalization and localization is to allow a single Web application to offer its content in
languages and formats tailored to the audience.

Django has full support for translation of text, formatting of dates, times and numbers, and time zones.

Essentially, Django does two things:

 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

Preparing the software for localization. Usually done by developers.

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.

=======================================================================

Django Web Development Tools

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.

DJANGO-EXTENSIONS This is a repository for collecting global custom management


extensions for the Django Framework.
Silky smooth profiling for
SILK

Django model mixins and


DJANGO-MODEL-UTILS utilities.

DJANGO-DEVSERVER A drop-in replacement for


Django's runserver.
DRF-YASG Automated generation of real
Swagger/OpenAPI 2.0 schemas
from Django REST Framework
code.
DJANGO-AUTOFIXTURE Can create auto-generated test
data.
NPLUSONE Auto-detecting the n+1 queries
problem in Python
Collection of Ansible
METAMON playbooks to quickly start
your Django Application

DJANGO-TEST-UTILS Utilities for testing Django


applications
DJANGO-SMUGGLER Django Smuggler is a pluggable
application for Django Web
Framework that helps you to
import/export fixtures via the
automatically-generated
administration
DJBLETS A collection of useful
extensions for Django.
DJANGO-MYSQL :dolphin: :horse: Extensions
to Django for use with
MySQL/MariaDB
DJANGO-ADMINACTIONS collection of useful django
actions to use with ModelAdmin
or AdminSite
[[[[[[Many more are there… pl refer the link above]]]]

========End of Django Tools======================

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:

 A recent version of Python 3 installed (Python 3.7 is the newest),


 The pip and venv tools (Recent versions of Python 3 comes with both of them bundled as
modules)
 The PostgreSQL database management system (alternatively you can also use SQLite for
database in development)

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.

Create a Virtual Environment & Install Django

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.

Installing the Geospatial Libraries (GDAL and PROJ.4)

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.

Create a Virtual Environment & Install Django


Creating a Django Project
You can now create a Django project using the django-admin.py script which will be available in
your terminal once your activate the virtual environment and install Django inside it:
$ django-admin.py startproject restaurants

Install PostgreSQL

In your terminal, run the following command to install PostgreSQL in your system if it's not
already installed:

$ sudo apt-get install postgresql

Creating a PostgreSQL Database

Create a database using the following command:

$ sudo -u postgres createdb mydb

You also need to install the psycopg2 PostgreSQL adapter for Python using pip

$ pip install psycopg2-binary

Installing PostGIS in your Database

You first need to connect to your created database using psql:

$ sudo -u postgres psql -d mydb

Next, you can to enable the postgis extension in your database:

$ CREATE EXTENSION postgis;

Configuring the PostgreSQL Database


Open the settings.py file and add django.contrib.gis.db.backends.postgis as the engine and use your
database credentials to connect to your PostgreSQL database:

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'
}
}

Change YOUR_POSTGIS_DATABASE_NAME, YOUR_DATABASE_USER_NAME and YOUR_DATABAS


E_USER_PASSWORD with your actual credentials.
Setting up GeoDjango in your Project
You can add GeoDjango to your project it by adding the gis module in your project's installed
apps.

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

============End of Django Overview=====================

Potrebbero piacerti anche