0% found this document useful (0 votes)
109 views40 pages

DJANGO

This document provides an introduction to web development using the Django framework in Python. It discusses object-oriented programming concepts like classes, objects, inheritance and polymorphism. It also covers Django specific topics like the MVT architecture pattern, modules, packages and advantages of using Django like being fast, secure, scalable and versatile. Constructors in Python are special methods used to initialize objects, and the document provides examples of default and parameterized constructors.

Uploaded by

Mohith Nakka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views40 pages

DJANGO

This document provides an introduction to web development using the Django framework in Python. It discusses object-oriented programming concepts like classes, objects, inheritance and polymorphism. It also covers Django specific topics like the MVT architecture pattern, modules, packages and advantages of using Django like being fast, secure, scalable and versatile. Constructors in Python are special methods used to initialize objects, and the document provides examples of default and parameterized constructors.

Uploaded by

Mohith Nakka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

WEB DEVELOPMENT USING 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

that can be imported inside another Python Program.

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.

The module contains the following components:

 Definitions and implementation of classes,


 Variables, and
 Functions that can be used inside another program.

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

Companies, organizations and governments have used Django to build all


sorts of things — from content management systems to social networks to scientific
computing platforms.

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

 Models: These represent data organization in a database. In


simple words, we can say that each model defines a table in the
data base and the relations between other models. It’s help us to
store every bit of data is stored in database
 Views: These contain all the information that will be sent to the
client. They make views that the final HTML document will
generate. We can associate the HTML code with views.
 Controllers: These contain all the actions performed by the
server and are not visible to the client. The controller checks
whether the user is authenticated or it can generate the HTML
code from a template.
 MVT
This is yet another design pattern similar to MVC. It is also used for
implementing web interfaces and applications but in contrast to MVC, the
controller part is taken care for us by the framework itself.  
 Models: This Model similar to MVC acts as an interface for
your data and is basically the logical structure behind the
entire web application which is represented by a database such
as MySqle, PostgreSQL.
 Views: The View executes the business logic and interacts
with the Model and renders the template. It accepts HTTP
request and then return HTTP responses.
 Template: The Template is the component which makes
MVT different from MVC. Templates act as the presentation
layer and are basically the HTML code B that renders the
data. The content in these files can be either static on
dynamic.

 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

and Django Template Language also known as DTL.

Below is an architecture diagram for MVT.

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

with this Django MVT architecture.

The Django Framework is based on this architecture and it actually communicates


between all these three components without needing to write complex code. That’s
why Django is gaining popularity.

 This architecture in Django has various advantages like:

1. Rapid Development

Actually, this Django architecture that separates in different components makes it


easy for multiple developers to work on different aspects of the same application
simultaneously. That is also one of the features of Django.
2. Loosely Coupled

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 an important aspect of development as there are different components in


Django architecture. If there is a change in different components, we don’t have to
change it in other components.

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 

1. Install Django- Install django by giving following command-


pip install django

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

This command creates a myapp folder in the folder of our project.


This folder contains five files:
 The init__.py file defines a package. Python needs it to differentiate between
the standard folders and the packages.
 The admin.py file is not useful at this moment. It contains the models that
need to be incorporated in the administration module.
 The models.py file contains all the models of our application. We use it a lot
for the development of our application. Models allow us to create our database
and store information.
 The tests.py file contains the unit tests of our application.
 The views.py file can contain views. This file will contain all the actions
before sending HTML page to the client.
Even though our new app exists within the Django project, Django doesn’t know
about it until we explicitly add it to django_project/settings.py file we can find
INSTALLED_APPS where you’ll see six built-in Django apps already there.

Add myapp at the bottom.

 USE OF ADMIN APP


The Django admin app can use your models to automatically build a site area
that you can use to create, view, update, and delete records. This can save you a lot of
time during development, making it very easy to test your models and get a feel for
whether you have the right data. 
The admin application can also be useful for managing data in production,
depending on the type of website. The Django project recommends it only for internal
data management (i.e. just for use by admins, or people internal to your organization),
as the model-centric approach is not necessarily the best possible interface for all users
and exposes a lot of unnecessary detail about the models.

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

Path(‘url_name/’,function_name,name=’name of the url’)

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

from myapp import views


 DYNAMIC URLS MAPPING
As per the programming terminology dynamic means related to runtime here
also we will provide input in runtime, For this dynamic url mapping we use
datatypes in the path 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

from django.http import HttpResponse


the ouput will be

from above we have just seen about static urls


For Dynamic URL
 INTERFACE BETWEEN CONTROLLER FILES
Now we are ready with urls.py and views.py but we have to give a connection
in between them to get functionality to our URL. In order to assign functionality to
the URL we have to import views from the user app,

 HTTP Request and Responses


HTTP (Hypertext Transfer Protocol) was initially created by Tim Berners-Lee
int 1989 and is the foundation of the World Wide Web. A network protocol is a set of
rules for formatting and processing data. It is like a common language for computers
that allows them to communicate with one another even if they are located on
opposite sides of the earth and have vastly different hardware and software.
HTTP is a request-response protocol that works in a client-server computing
model. Every time you visit a webpage an initial "request" is sent by the "client" (i.e
your computer) and a "response" is sent back by a "server." The client doesn't have to
be a computer though, it could also be a mobile phone or any internet-connected
device. But the process is the same: an HTTP request is sent to a URL by a client and
a server sends back an HTTP response.
Ultimately, all a web framework like Django does is accept HTTP requests to
a given URL and return a HTTP response containing the information necessary to
render a webpage. That’s it, Generally this process involves identifying the proper
URL, connecting to a database, adding some logic, applying style with
HTML/CSS/JavaScript/static assets, and then return the HTTP response.

The abstract flows looks like this:

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

Next, we need to update django_siva5e1/settings.py to tell Django the location of our


new templates directory. This is a one line change to the setting “DIRS” under
templates
Now a new file is created in templates. So, rename it with a new file name with .html
extension.
Within the templates directory create a new file basic.html

 Providing Interface between controller and templates


The python and HTML script is separated with help of views and templates. To
link the two together we have to rely on the Django Template Language (DTL)
and
render function.
Syntax to render function is,
render(request,PATH,{dictionary_parameters})
where, request – this is our initial request
PATH – this is the path of template
{dictionary_parameters} – it contains required variables for template

Static File Handling


Websites generally need to serve additional files such as images, JavaScript,
or CSS. In Django, we refer to these files as “static files” in Django. Django
provides django.contrib.staticfiles to help you manage them.
1. Include the django.contrib.staticfiles in INSTALLED_APPS in
siva5e1/settings.py. In default, the settings.py includes
django.contrib.staticfiles in it.
2. Define STATIC_URL in settings.py file

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

4. Load static files in the templates


{ % load static % }
5. You can use the css file by link tag, .js file by script tag and .jpg file by image
tag in any template

Benefits of Static Files

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

DATA RENDERING FROM  HTML TO VIEWS AND


THEN VIEWS TO  HTML WITH EXAMPLE
Consider a project named siva5e1 having an app named myapp.
After you have a project and an app, open views.py and let’s start creating a view
called sample_view which is used print “Hello world” through a template file. A
django view is a python function which accept an argument called request and
returns an response.
Enter following code into views.py of app.but this code won’t work until into define
a proper mapping of URL. Mapping means you need to tell Django what a user
enters in the browser to render your particular view.So let’s modify urls.py to start
our view.
 This way you can render any template file using the same procedure –
1. Create a view in views.py

2. Create a template file which is to be rendered and link it to the view.

3. Create a URL to map to that view.

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

 There are multiple fields for different input elements in Django.


Some types of fields in Django:

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

Model Quiries(Django Shell)

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

- if u want to retriev e entire db

- ob=classname.objects.all()

- ob=Student.objects.all()

- ob

- if u want to access individual columns

for i in ob:

print(i.name)

print(i.age)

- if u want to return list format

ob=modelname.objects.values_list()

ob

- if u want to access unique data(specific data)

- get()

- data=classname.objects.get(id=3)

data

- if u want to access multiple data(duplicates)

- filter()

- data=class.objects.filter(name='siri')

- data

-if u want to access first

class name.objects.first()

-if u want to access last

class name.objects.last()
slicing:::

info=classname.objects.all()[:3]

info

Data updating:

-to update a specific field in all records

address=srikakulam

info=Student.objects.all().update(address='srikakulam')

info

to update specific records-we have to fetch data from db

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

After creation of superuser open chrome and then type localhost:8000/admin


Then a page will appear as
sm

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

Enter the details of the user we want to add


Enter complete details

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

Your Superuser is created Successfully.

Now login into the Superuser by localhost:8000/admin/

Fill the username and password

Roles of the superuser

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.

There are two main types of Django user classes: User and AnonymousUser. If a user


authenticates himself (i.e. provides a valid username/password) Django recognizes
him as a User. On the other hand, if a user just surfs an application without any
authentication, Django recognizes him as an AnonymousUser.

Any User can be further classified into one of various sub-types:

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

In addition, you can assign Django permissions granularly to a User or Group in order


for them to do CRUD(Create-Update-Delete) records on Django models, a process
which is done through Permission model records. Or you can also assign coarser
grained Django permissions on url/view methods or template content to grant access
to a User, Group or even Permission assignee.

CRUD operations, Message Passing

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

The URL for model CRUD operation is like this


The views will be like this:

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.

There are 2 different types of validations:

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.

There are different ways of form validation we can use.

1. Validation of a Particular Field

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

ValidationErrors are built in methods and subclasses of Django. They are used in


models too

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

3. Validation using Validators

 A validator is like a function which is callable. We basically use them to raise


ValidationErrors if some conditions aren’t fulfilled.

.4. Custom Validators

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

Next set up the Gmail for Django mail API

1.After that create forms

2.Create Views

3.Create two templates


a. index.html

b.success.html

4. we can configure our URLs in Django

Now run the Server.

User Registration and User Authentication:

Make a form for the Registration in forms.py


Create Views

Now make a model in Models.py and make migration and migrate


Now Create templates
1.For registration
reg.html

 2.For displaying details


display.html
3.For Updating the details
updatenew.html

4.For Deleting the details


deletenew.html
Now configure our URLs in Django

Now run the server


http://localhost:8000/reg/
For displayind details

Here We can update or Delete the Data


Data is stored in the Data Base

File Creation And User Profile Creation


File uploading and handling have many approaches in Django. We will use models to
implement file upload in Django. We are using model forms in this example.

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

MEDIA_ROOT is an empty string by default. It takes in the absolute file path of a


directory. We have used the same join functions in Django static files
tutorial that we have passed in the file path of media directory. This directory will
store all the files a user uploads in Django.
Although you can directly give the path as a string in MEDIA_ROOT. It has its own
problems. That approach will raise errors when you upload the file in the production
environment. Always try to use dynamic URLs which are relative to the project
directory. Like we used join method in the above setting.

2. MEDIA_URL

MEDIA_URL works the same way as STATIC_URL. This URL is used by Django


instead of serving files with an absolute path. When Django will serve an uploaded
file media it will be automatically added to the URL.
Remember MEDIA_ROOT & MEDIA_URL can have totally different values. The
directory name is not required to be same. You can name MEDIA_URL anything.

A User Profile Application

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.

Now, install the new application in settings.py file.

2. Make Models

 profile_maker/models.py file.

3. Make Forms

Make a new forms.py file in your application. Inside profile_maker/forms.py file,


paste this code:
Here we are using things called model forms. These forms are special and are very
handy.
Model 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.

Models forms are a subclass of forms. When we make a form


using ModelForm class, we use META class. In META, there are two attributes
required, they are:
 model: It takes in the name of the model. We have to import
the User_Profile model for this. This attribute defines the model to render a
form. This form object is then used to save the user data to be stored directly in a
database.
 fields: It is a list of strings. This list will take the name of the fields in the
model. This field defines input fields for a form. We specify the fields from
models in this list. All the fields mentioned in this list will be used to create a
form.
That’s all the information on model forms, we require for this tutorial.

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

Now, again make a templates folder. The directory pattern will


be profile_maker/templates/profile_maker. Remember to make two directories.
First is templates and then the profile_maker directory inside it.
Now, make a new file
in profile_maker/templates/profile_maker named create.html.

Now, make a new file named details.html in the same directory

Now, make a new file named error.html in the same directory

6. Configure URLs

We have made all the files. Open your main urls.py


Then make a new file in profile_maker/ directory named urls.py

Now, run and test your application

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.

You might also like