DJANGO
DJANGO
INTRODUCTION TO PYTHON
OBJECT-ORIENTED PROGRAMMING
The main goal of OOP are to provide a logical mapping between code and
real-life problems and to promote code reuse and sharing. OOPs in Python is a
programming approach that focuses on using objects and classes as same as other
general programming languages.
Features of Object Oriented programming:
1. Class
2. Objects
3. Methods
4. Inheritance
5. Polymorphism
6. Delegation
7. Message passing
8. Containership
9. Reusability
10. Data Abstraction
11. Data Encapsulation
Class:
Class is a logical entity which contains data members and member functions.
we can also called as blue print and the data is accessed by objects. To create a class
in Python, you need to provide the class keyword.
Syntax : class class_name
Object:
It is a runtime entity, which is used to access the class data
. Python allows developers to develop applications using the OOPs approach with the
major focus on code reusability. It is very easy to create classes and objects in Python.
CONSTRUCTOR:
Constructors are generally used for instantiating an object. The task of constructors
is to initialize(assign values) to the data members of the class when an object of the
class is created. In Python the __init__() method is called the constructor and is
always called when an object is created.
Syntax of constructor declaration :
def __init__(self):
There are two types of constructors:
1.default constructor:
The default constructor is a simple constructor which doesn’t accept any arguments.
Its definition has only one argument which is a reference to the instance being
constructed.
Example
class default_constructor:
def __init__(self):
self.i = "Welcome to Django"
def print(self):
print(self.i)
obj = default_constructor ()
obj.print()
2.parameterized constructor:
Constructor with parameters is known as parameterized constructor. The
parameterized constructor takes its first argument as a reference to the instance
being constructed known as self and the rest of the arguments are provided by the
programmer.
Example
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " +
str(self.second))
print("Addition of two numbers = " +
str(self.answer))
def calculate(self):
self.answer = self.first + self.second
obj = Addition(1000, 2000)
obj.calculate()
obj.display()
INHERITANCE:
Inheritance allows us to define a class that inherits all the methods and properties
from another class.
BASE CLASS
Base class is the class being inherited from,
also called base class.
Derived class is the class that inherits from another class,
also called derived class.
DERIVED CLASS
Types of inheritance
Single Inheritance
Multi-Level Inheritance
Multiple Inheritance
Multipath Inheritance
Hierarchical Inheritance
Hybrid Inheritance
MODULE:
In Python, Modules are simply files with the “.py” extension containing Python code
In simple terms, we can consider a module to be the same as a code library or a file
that contains a set of functions that you want to include in your application.With the
help of modules, we can organize related functions, classes, or any code block in the
same file.
Using import keyword we can import all the functions, definitions in some other
source file
import module
example: import math
from module import variables/definition/function
example: from math import sqrt, pi
from module import *
# The * symbol used with the from import statement is used to
.import all the names from a module to a current namespace
example: from math import*
PAKAGES:
A package is a hierarchical file directory structure that has modules and other
packages within it. Like modules, you can very easily create packages in python.
Remember that, every package in Python is a directory which must have a special file
called _init__.py. This file may not even have a single line of code. It is simply added
to indicate that this directory is not an ordinary directory and contains a Python
package. In your programs, you can import a package in the same way as you import
any module. For example, to create a package called MyPackage, create a directory
called MyPackage having the module MyModule and the _init__.py file. Now, to use
MyModule in a program, you must first import it. This can be done in two ways.
import MyPackage.MyModule
or
from MyPackage import MyModule
Django is also a package which contains several modules in it which are used for web
frame work.
DJANGO
INTRODUCTION TO DJANGO
Django was born in 2003 in a press agency of Lawrence, Kansas. It is a web
framework that uses Python to create websites. Its goal is to write very fast dynamic
websites. This framework uses the MVC pattern, which enables us to have a coherent
architecture.
Today, big organisations such as the Instagram mobile website, Mozilla.org
and Openstack.org are using Django.
Features of Django
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.
Exceedingly scalable.
Some of the busiest sites on the web leverage Django’s ability to quickly and
flexibly scale.
Incredibly versatile
Advantages of Django
Django is published under the BSD license, which assures that web -
applications can be used and modified freely without any problems: it's also
free.
Django is fully customizable. Developers can adapt to it easily by creating
modules or overridden framework methods.
This modularity adds other advantages. There are a lot of Django modules that
you can integrate into Django. You can get some help with other people's
work because you will often find high-quality modules that you might need.
Using Python in this framework allows you to have benefits from all Python
libraries and assures a very good readability.
Django is a framework whose main goal is perfection. It was specifically.
made for people who want clear code and a good architecture for their
applications. It totally respects the Don't Repeat Yourself (DRY) philosophy,
which means keeping the code simple without having to copy/paste the same
parts in multiple places.
With regards to quality, Django integrates lots of efficient way to perform unit
tests
MVC
The MVC pattern was created to separate logic from representation and have
an internal architecture that is more tangible and real. The Model-View-
Controller(MVC) represents the three application layers that the paradigm
recommends
ARCHITECTURE OF DJANGO
As mentioned, Django follows the MVT framework for architecture.
MVT is generally very similar to that of MVC which is a Model, View, and
Controller. The difference between MVC and MVT here is the Django itself does the
work done by the controller part in the MVC architecture. Django does this work of
controller by using templates. Precisely, the template file is a mixture of HTML part
The Template handles the UI and architecture part of an application. The view
does the logical part of the application and interacts with the Model to get the data and
in turn modifies the template accordingly. Here as already mentioned, Django works
as a controller and gets a URL that is linked to the view part of the application and
thus transports the user responses to the application. This complete interaction is dealt
1. Rapid Development
This architecture of Django has different components which require each other at
certain parts of the application, at every instant, that increases the security of the
overall website. As the model file will now only save on our server rather than saving
on the webpage.
3. Ease of Modification
This is actually one of the special features of Django, as here it provides us with much
more adaptability of our website than other frameworks.
DJANGO INSTALLATION
Install python3 if not installed in your system
After the installation has completed, you can verify your Django installation by
executing django-admin --version in the command prompt.
After installation of idle install DB browser sqlite its our choice. Which provides
database for our projects.
PROJECT CREATION
Before you start using Django, you need to create an environment for your
applications. We will create a Django project. This project will then contains our
applications
To create the project of our application, we need to run the following
command using the django-admin.py file
django-admin.py startproject siva5e1
This command creates a siva5e1 folder in the folder from where you run the
command. We will find a folder and a file in that folder:
The manage.py file will be used for actions performed on the project such as
starting the development server or synchronizing the database with the
models.
The siva5e1 folder represents an application of our project. By default, the
startproject command creates a new application.
This folder contains two very important files:
The settings.py file contains the parameters of our project. This file is common
to all our applications. We use it to define the debug mode, configure. the
database, or define Django packages that we will use. The settings.py file
allows us to do more things, but our use will be limited to what has been
previously described.
The urls.py file contains all our URLs. It is with this file that we make the
routing in Django.
APP CREATION
We will not program our application in the project folder because we want to
create our own application.
For this, run the following command using the manage.py file created by the
startproject command You must run the following command in the project folder
which contains manage.py file:
manage.py startapp myapp
After creating all of this run the server in the location of manage.py file present
In that cmd enter python manage.py runserver then it will show like this if anything
error in code we get details cmd
Then open chrome enter a 127.0.0.1:8000 in urls search at top of the window
Then a page will appear as
URL MAPPING(CREATION)
Well, till here, we have learned to create a model, view, and template. Now,
we will learn about the routing of application.
Since Django is a web application framework, it gets user requests by URL locater
and responds back. To handle URL, django.urls module is used by the framework.
Let's open the file urls.py of the project and see the what it looks like:
Already a path is created with the name of admin which we have discussed
previously about admin site where we can handle our user app. For making another
path for that we have to follow the structure
Ex:
from picture we can see another path is created ,but here we mentioned views.sample
before this we have to import views.py into urls.py as
Path(‘urlsname/<datatype:variable_name>/’,function_name(views),name=’name
of the url’)
Ex:
VIEWS:
Django Views are one of the vital participants of MVT Structure of Django.
As per Django Documentation, A view function is a Python function that takes a Web
request and returns a Web response. This response can be the HTML contents of a
Web page, or a redirect, or a 404 error, or an XML document, or an image, anything
that a web browser can display.
Django views are part of the user interface — they usually render the
HTML/CSS/Javascript in your Template files into what you see in your browser when
you render a web page. (Note that if you’ve used other frameworks based on the
MVC (Model-View-Controller), do not get confused between Django views and
views in the MVC paradigm. Django views roughly correspond to controllers in
MVC, and Django templates to views in MVC.)
From the above two urls we have to create a functions in views.py in views we
can create functions as well as class
For static url using HttpResponse
def sample(request):
return HttpResponse(“Hello world”)
before this we need to import HttpResponse into the views.py file from django.http
as
Django
combines
HTTP Request URL HTTP Response
database, logic,
styling
Django Templates
Every web framework needs a convenient way to generate HTML file and in
Django the approach is to use templates: individual HTML files that can be linked
together and also include basic logic.
By default, Django’s template loader will look within each app for related
templates. However the structure is somewhat confusing: each app needs a new
templates directory, another directory with the same name as the app, and then
template file.
We create a new templates directory, a new directory with the name of the app ,
myapp, finally our template will be added in it.
In this approach the Django template loader wants to be really sure it finds the
correct template! For example we are having basic.html file within two separate app.
This Structure makes sure there are no such conflicts.
There is, however, another approach which is to instead create a single project level
templates directory and place all templates within there. By making a small tweek to
our django_siva5e1/settings.py file we can tell Django to also look in this directory
for templates. This is the approach we’ll use
First, quit the running server with the ctrl+c command. Then create a directory called
templates
3. Now create a new directory with name static which includes three sub
directories CSS, JS, images which includes files with extensions of .css, .js
and .jpg respectively
They are static: These files don’t change until the developer replace them with a
new one. Thus, the server just fetches them from the disk, taking a minimum
amount of time.
Static files are easier to cache: They don’t change and are not modified by the
server. That makes the performance faster.
Static files are energy efficient: Static files are fetched from the disk when
required. They require no processing which saves the processing overhead and
website response becomes fast.
Include your app’s urls into main urls by adding following code to > urls.py.Now
lets create a path to our view from > urls.py
MODELS
Django web applications access and manage data through Python objects referred
to as models. Models define the structure of stored data, including the field types and
possibly also their maximum size, default values, selection list options, help text for
documentation, label text for forms, etc.
The definition of the model is independent of the underlying database — we can
choose one of several as part of your project settings. Once we've chosen what
database we want to use, we don't need to talk to it directly at all — we just write your
model structure and other code, and Django handles all the dirty work of
communicating with the database for us
First we have to open model.py file in userapp and write the required code using
class
BooleanField
CharField
ChoiceField
DateField
DecimalField
EmailField
FileField, etc.
Some common attributes to these fields can be used for more control. These attributes
come in handy when validating data. They provide a more constrained selection of
data.
MIGRATIONS
Migrations are Django’s way of propagating changes you make to your models
(adding a field, deleting a model, etc.) into your database schema. They’re designed to
be mostly automatic, but you’ll need to know when to make migrations, when to run
them, and the common problems you might run into
migrate, which is responsible for applying and unapplying migrations.
makemigrations, which is responsible for creating new migrations based on the
changes you have made to your models.
You should think of migrations as a version control system for your database
schema. makemigrations is responsible for packaging up your model changes into
individual migration files - analogous to commits - and migrate is responsible for
applying those to your database.
After the completion of command entering in cmd an interface file will be
generated in myapp/migrations as 0001_initial_
ORM
The Django web framework includes a default object-relational mapping layer
(ORM) that can be used to interact with application data from various relational
databases such as SQLite, PostgreSQL and MySQL.
ORMs have certain benefits over the traditional approach. The main advantage
ORMs provide is rapid development. ORMs make project more portable. It is easier
to change the database if we use ORMs.Django is shipped with its own ORM. It is a
very efficient ORM and is tightly coupled with the Django framework. Django ORM
is suitable for handling low-medium complexity queries.
Django ORM provides a level of abstraction which makes it easy to work with
objects. ORM will automatically relate the object’s attributes to corresponding table
fields. We are going to make some models and check their field relationships in other
tables.
We all use queries to retrieve data from the database. Querysets are Django’s way to
retrieve data from the database. The Django ORM lets us use Querysets.
A Queryset is a list of objects of a model. We use Querysets to filter and arrange our
data. These make our work as a Python developer easier. The Model Quiries as
follows
- ob=classname.objects.all()
- ob=Student.objects.all()
- ob
for i in ob:
print(i.name)
print(i.age)
ob=modelname.objects.values_list()
ob
- get()
- data=classname.objects.get(id=3)
data
- filter()
- data=class.objects.filter(name='siri')
- data
class name.objects.first()
class name.objects.last()
slicing:::
info=classname.objects.all()[:3]
info
Data updating:
address=srikakulam
info=Student.objects.all().update(address='srikakulam')
info
info=Student.objects.get(id=2)
info
info.address='guntur'
info.save()
info
SUPERUSER CREATION
Super user is an admin to the user application. Super user is able to perform the
CRUD (create, read, update, delete) operations on database directly from the
respective panel facilitated by django. We have seen a login for admin is visible
when we browse server URL followed by admin/. Now it’s time to generate
admin login credentials as a super user.
To create super user open command prompt/terminal at manage.py file location
and run the following command,
python manage.py createsuperuser
(Note : if any operational error occurs run – python manage.py migrate and run
above command)
Now
ROLES OF SUPERUSER
Previously we have created a superuser with userid and password enter in the above
fields and click on login. Then we see the page as
Here, we can add a user to our project and groups also so he can use our project only
some
But, admin can access anything related to project, If we ant to add click on add
Click on save
v
Siaram [email protected]
Figure 1
After adding a user the page will appear as above , if you want to add another user
click on add
Superuser Creation
Django provides us Admin Panel for it’s users. So we need not worry about
creating a separate Admin page or providing authentication feature as Django
provides us that feature. Before using this feature, you must have migrated your
project, otherwise the superuser database will not be created.
For creating superuser, first reach the same directory as that of manage.py and run
the following command:
Then enter your username, email, password and confirm your password
In order to view and create records we also need this user to have permissions to
manage all our objects. You can create a "superuser" account that has full access to
the site and all needed permissions using manage.py.
superuser.- The most powerful user with permissions to create, read, update
and delete data in the Django admin, which includes model records and other
users.
staff.- A user marked as staff can access the Django admin. But permissions to
create, read, update and delete data in the Django admin must be given
explicitly to a user. By default, a superuser is marked as staff.
active.- All users are marked as active if they're in good standing. Users
marked as inactive aren't able to authenticate themselves, a common state if
there's a pending post-registration step (e.g. confirm email) or a user is banned
and you don't want to delete his data.
Django also offers the concept of a Group class to grant a set of users the same set of
permissions without having to assign them individually.
For example, you can grant permissions to a group and then assign users to the group
to make permission management easier. In this manner, you can revoke or add
permissions in a single step to a set of users, as well as quickly give new users the
same permissions.
CRUD stands for Create, Read, Update & Delete. These are the four basic operations
which are executed on Database Models. We are developing a web app which is
capable of performing these operations.
Since we are developing a library app, let’s take an example of the same. In a library,
books are objects. The books have attributes like name, author, etc. We need an
application which can perform CRUD operations on book object. The CRUD
operations are defined as follows:
1. Read Operation
The ability of the application to read data from the database.
2. Create Operation
The ability of the application to store data in the database.
3. Update Operation
The ability of the application to edit the stored value in the database.
4. Delete Operation
The ability of the application to delete the value in the database
FORM validation
Forms are a collection of HTML elements to take input from the user. In simple
words, whenever you give any kind of instruction or input on web, that is known as a
form.
The input elements come inside <form></form> tags. It is collectively called as
HTML form.
1. Custom validations
2. Built-in validations
Form validation means verification of form data. Form validation is an important
process when we are using model forms. When we validate our form data, we are
actually converting them to python datatypes. Then we can store them in the database.
This validation is necessary since it adds that layer of security where unethical data
cannot harm our database.
We use this Validation when we need to valid only one particular Field For
example
We are concerned to valid a password field which should have max length of 8
def clean_password(self):
password = self.cleaned_data['password']
if len(password) >8:
raise forms.ValidationError("password is too short")
return password
2. Using is_valid()
You can use is_valid() when required to validate complete form-data. This validation
will check for Python-datatypes. This function will return True or False
Suppose you have some fields which you want to validate and there may be no built-
in validator of your use-case. Then, you can create your own custom validators.
1. Just declare a function with the parameter value. The parameter name shall be
that.
2. Then, perform your desired validations on value. When value satisfies any
criteria raise a ValidationError
3. Add that function_name in validators argument of the chosen field, just as we
used validators.
Mail Sending
We all have used the email feature of websites, whenever we forget our
password or subscribe to any website, etc. Every time an email is sent to our inbox
by the website including the link to reset the password.
To send an email….
We need to add some settings in settings.py
EMAIL_BACKEND
This setting specifies the backend that we are going to use for sending an email in
Django. There are multiple backends that Django provides.
EMAIL_HOST
This setting is to specify your email service provider. We are using the setting for
Gmail.
EMAIL_HOST_USER
It is the account name from which we will send an email.
EMAIL_HOST_PASSWORD
The password of the email account that we are using.
EMAIL_PORT
This is the setting for Gmail, you can get yours on the web. It is the port used by the
SMTP server.
EMAIL_USE_TLS
This setting specifies whether the Email uses a TLS connection or not. It is True for
Gmail.
EMAIL_USE_SSL
False for Gmail
2.Create Views
b.success.html
Configuring Settings
Before any file upload application, these settings are necessary. Open
project’s settings.py file and add these lines below the STATIC FILES settings.
1. MEDIA_ROOT
2. MEDIA_URL
Now, we will make an application which can store a user’s profile in Django. This
profile will have some basic information and a profile picture. We will also make a
form to upload the picture. We will learn some important concepts of doing same in
Django
Media directory exists at the same level as manage.py file.
2. Make Models
profile_maker/models.py file.
3. Make Forms
The basic concept of model forms is that they derive their structure from models. Yes,
that’s right, we don’t have to define a form and connect it with models. We can do
that directly via model forms.
So basically, we will get a form with the fields defined in fields attribute of Form. It’s
a very common practice to use model forms but is not necessary.
4. Make Views
The views are simple to understand. We have imported the models and forms in this
view file. Then we have defined a list IMAGE_FILE_TYPES. We use it to check
the type of file.
Then our function definition starts.
In this function, we have defined a form object. It will render a form. Then we are
using form validation to clean our form data. This function returns True or False. If
the form has valid data, we can store the data locally. Then we are extracting the file
type uploaded by the user.
Since we are using file field, we have multiple attributes. The file URL contains the
filetype after the ‘.’. We have used a basic string function split() for this purpose.
The split() will split the string into parts where ‘.’ is present. You can get more on this
in basic Python functions. In the next line, we are making it a lower type string.
Then we are performing a check whether the file is an image file or not. We can skip
this part if we use the image field.
So, if the file is not an image file, it will render error.html.
Otherwise, it will render details.html, showing the details we just filled. If the form is
rendered for the first time, it will render create.html. Now, we understood the view
function. Let’s make our templates.
5. Create Templates
6. Configure URLs
TEMPLATES BLOCKS
For template blocks — Django's template language is designed to strike a balance
between power and ease. {% block %}{% endblock %}: This is used to define sections
in your templates, so that if another template extends this one, it'll be able to replace
whatever html code has been written inside of it. Blocks are identified by their name.
Usage: {% block content %} <html_code> {% endblock %} .
2 ) Extend it in blog.html like,
{% extends 'base.html' %}
{% block content %}
# write your blog related code here
{% endblock %}
# None of the code written here will be added to the template
Here we extended the base layout so its HTML layout is now available in
the blog.html file.The concept of { % block %} is template inheritance
which allows you to build a base “skeleton” template that contains all the
common elements of your site and defines blocks that child templates can
override.