0% found this document useful (0 votes)
35 views41 pages

E-Note 24867 Content Document 20240927094010AM

Class Notes

Uploaded by

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

E-Note 24867 Content Document 20240927094010AM

Class Notes

Uploaded by

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

Django

Deepak H G
Introduction to Python and Django
Introduction to Django

 What is Django?
 Django is a free, open source web framework written in the Python programming
language.
 Django encourages rapid application development with clean and realistic design.
 Django was first released in 2005. The current version is 5.1.
 Django powers many of the largest websites in the world including Instagram,
Pinterest, Bitbucket, and Disqus.
 Django is a popular choice for early-stage startups and side projects.
Introduction to Django

 Web Framework
 A collection of tools that abstract away much of the difficulty–and repetition–inherent in
web development:
 Ability to connect to a database.
 Set URL routes.
 Display content on a page.
 Handle security
 Rather than recreate all of the above from scratch, programmers over the years have
created web frameworks in all the major programming languages.
 Popular Web frameworks:
 Rails in Ruby
 Laravel in PHP
 ASP.NET in C#
Introduction to Django

 Why Django?
 Django is free and open source.
 Django is built by experienced developers.
 With Django, web application development can be taken from concept to launch in a
matter of hours.
 Django makes a web developer to focus on writing the application without needing to
reinvent the wheel.
 Django takes security seriously and helps developers avoid many common security
mistakes.
 Companies, organizations and governments have used Django to build all sorts of
applications — from content management systems to social networks to scientific
computing platforms.
 Django remains under active development with a regular release schedule of monthly
security/bug fixes and a major new release every 8 months.
The Django Philosophy

 Don’t repeat yourself


 A general principle to prevent duplication.
 The principle seeks to prevent the repetition of the same code in different parts of
a project, or the re-implementation of a feature already provided by the
framework or library.
 A deep knowledge of the framework’s capabilities and features is a must to
prevent breaking the DRY.
The Django Philosophy

 Loose coupling and High cohesion


 Principles for creating maintainable, modular, and efficient code.
 Loose coupling refers to how much the modules or components of your application
are independent of each other. Having Loose coupling allows developers to make
changes to modules without affecting others.
 High cohesion refers to how modules are functionally related i.e. a module must
perform a specific task.
 Less code and quick development
 Applications should be lean and without a boilerplate (sections of code that have
to be included in many places with little or no alteration).
The Django Philosophy

 Explicit is better than implicit


 Code should not hide its behavior or reply to implicit operations. When reading the
code, there should not be any hidden operations and the programmer’s intent
should be transparent.
 Models: Include all relevant domain logic
Setting Up the Development Environment
Introduction to Development Environments

 Installing Python
 Django 5.0 supports Python 3.10, 3.11, and 3.12.
 Linux and macOS have Python preinstalled.
 For Windows, download Python from Download Python | Python.org
 Verify Python 3 is installed on the machine by typing the command:

 Note: Python 2 has reached end-of-life in January 2020 and shouldn’t be used.
Introduction to Python

 Installing Python
 Django 5.0 supports Python 3.10, 3.11, and 3.12.
 Linux and macOS have Python preinstalled.
 For Windows, download Python from Download Python | Python.org
 Verify Python 3 is installed on the machine by typing the command:

 Note: Python 2 has reached end-of-life in January 2020 and shouldn’t be used.
Understanding Python Virtual Environment

 To develop Python applications, we use packages and modules that are not
included in the standard Python library.
 We may have Python applications that require a different version of the same
module.
 Only a specific version of a module can be installed system-wide.
 If we upgrade a module version for an application, it may break other applications
that require an older version of the module.
 The solution is Python Virtual Environments.
 With virtual environments, Python modules are installed in an isolated location
rather than system-wide.
 Each virtual environment has its own Python binary and can have its own
independent set of installed Python packages.
 Creating lightweight virtual environments is supported by Python venv library.
Python Virtual Environment

 Creating Python Virtual Environment


 python –m venv <venv_name>
 The above command creates a Python environment in a new directory
<venv_name>
 Command to activate the virtual environment:
<venv_name>\Scripts\activate – On Windows
source <venv_name>/bin/activate – On Linux or macOS
 Any Python libraries installed, while the virtual environment is active, will go
into: <venv_name>\lib\python3.12\site-packages.
 The virtual environment can be deactivated at any time with the deactivate
command.
Installing Django

 Django comes as a Python module and can be installed in any Python environment.
 Upgrading pip – the package management system
 python -m pip install --upgrade pip

 Installing Django with pip


 pip install Django
 This will install Django’s latest version in the site-packages directory of the virtual
environment. (.\djangoenv\Lib\site-packages)
 Check Django installation
 python –m django –-version
 Django is successfully installed if the output is the version number of Django.
 Django is not installed if we get the message No module named Django.
Django framework components

 Django is a framework consisting of a set of components that solve common


web development problems.
 Django follows the MTV (Model-Template-View) pattern.
 MTV is slightly similar to well-known MVC (Model-View-Controller) pattern,
where the template acts as a view and the framework itself acts as the
controller.
Django framework components

 The responsibilities in the Django MTV pattern are:


 Model
 Defines the logical data structure and is the data handler between the database and the view.
 Template
 The presentation layer. Django uses a plain-text template system that keeps everything that the
browser renders.
 View
 Communicates with the database via the model and transfers the data to the template for
viewing.

 The framework itself acts as the controller. It sends a request to the appropriate
view, according to the Django URL configuration.
 When developing any Django project, we work with models, views, templates, and
URLs.
The Django architecture

 The main components of the Django framework are:


 Models
 Views
 Templates
 URLs
Django framework components

 How Django handles HTTP requests and generates responses?


 A web browser requests a page by its URL and the web server passes the
HTTP request to Django.
 Django runs through its configured URL patterns and stops at the first
one that matches the requested URL.
 Django executes the view that corresponds to the matched URL pattern.
 The view potentially uses data models to retrieve information from the
database.
 Data models provide data definitions and behaviors. They are used to
query the database.
 The view renders a template (usually HTML) to display the data and
returns it with an HTTP response.
 Django also includes hooks in the request/response process, which are called middleware.
Django Projects and Apps
Django Project Versus Django Application, creating a new Django project, The Django project
structure, Creating the Django app, Understanding the Django App structure, MVT design patterns
in Django, Running the Django App.
Projects and Applications

 Project
 A Django installation with some settings.
 Comprises one or more Django applications.
 A project has database settings, application-specific settings, templates, static files, and
more.
 Represents the entire application we are building.
 Application
 A module made to perform a specific function.
 A group of models, views, templates, and URLs.
 Applications interact with the framework to provide specific functionalities.
 Applications may be reused in various projects.
 Project = Website, containing several applications like blog, wiki, or forum.
Creating the first project

 Command to create the Django project:


 Django-admin startproject <project_name>
 Project Structure
 The outer mysite directory is the container for the project.
 manage.py – Command-line utility to interact with the project. Used to start new
applications, run a development server, create migrations, execute migrations, and
more.
 mysite/ - Python package for the project.
 __init__.py – An empty file that tells Python to treat the mysite directory as a
Python module.
Creating the first project

 Project Structure
 asgi.py – Stands for Asynchronous Server Gateway Interface. Configuration to run
the project as an ASGI application with ASGI compatible web servers. Emerging
Python standard for asynchronous web servers and application.
 settings.py – Settings and configuration for the project. Contains initial default
settings. Includes settings for database connections, installed apps, middleware
classes, template configs, and internationalization.
 urls.py – File to define patterns for URLs and associate them with the views.
 wsgi.py – File stands for Web Server Gateway Interface. It’s a specification that
describes how a web server communicates with web applications. Django uses the
WSGI standard as one of the interfaces to communicate with the web server.
Applying initial database migrations

 Applications require a database to store data.


 The settings.py file contains the database configuration for the project in the
DATABASES setting:

 The default configuration is for SQLite3 database.


 Django applications contain data models that are mapped to database tables.
 To complete the project setup, the tables associated with the models of the
default Django applications, included in the INSTALLED_APPS setting, to be
created.
Applying initial database migrations

 Run the following command for database migrations:


 python manage.py migrate
 The tables for the applications listed in the INSTALLED_APPS setting are
created in the database.
Running the Development Server

 Django comes with a lightweight web server to run the code quickly.
 The Django development server, keeps checking for the code changes, while
running, and reloads automatically.
 Start the development server using the command:
 python manage.py runserver
 Open http://127.0.0.1:8000/ in the browser.
 Each HTTP request is logged in the console by the development server.
 Any error that occurs while running the development server will also appear in the
console.
 Note: The server is intended only for development and not suitable for
production use.
 To deploy Django in a production environment, use WSGI web server (Apache) or
ASGI server (Daphne or Uvicorn).
Project Settings

 Open settings.py file.


 DEBUG
 Turns the debug mode of the project on and off.
 If set to True, Django will display detailed error pages when an uncaught exception
is thrown by the application.
 Remember to set to False on Production environment.
 ALLOWED_HOSTS
 Not applied when debug mode is on or when the tests are run.
 Add domain/host to this setting to allow it to serve Django site when the site is
moved to production.
Project Settings

 INSTALLED_APPS
 Tells Django which applications are active for the current site.
 By default, Django includes the following applications:

 MIDDLEWARE
 List containing the middleware to be executed.
Project Settings

 ROOT_URLCONF
 Python module where the root URL patterns of the application are defined.
 DATABASES
 A dictionary containing the settings for all the databases to be used in the project.
 There must always be a default database.
 LANGUAGE_CODE
 Default language code for the Django website.
 USE_TZ
 Tells Django to activate/deactivate time zone support.
Creating an application

 Run the following command in the command prompt from the project’s root directory:
 python manage.py startapp <application_name>
 Basic structure of the application:
 __init__.py: An empty file that tells Python to treat the <application_name> directory as a
Python module.
 admin.py: To register models to include in the Django administration site.
 apps.py: The configuration file for the application.
 migrations: Contain database migrations of the application.
 models.py: The data models of the application. All applications to have models.py.
 tests.py: To add tests for the application.
 views.py: The logic of the application goes here.
 Creating the application entry in settings.py
 Add the application configuration entry in INSTALLED_APPS.
Django Models and MySQL
Understanding Django models, Creating the first model, Django’s database API: Create, retrieve, update, and
delete operations, Understanding Django migrations, Django’s admin interface: Registering models and
manipulating data, Introduction to Django’s ORM: Queries and aggregations, Extending the models, Ensuring
data integrity with model constraints.
Django models

 The relational model organizes data using relations represented as tables.


 A table is a collection of rows.
 Each table in the database represents a specific entity.
 Entities have attributes that are mapped to columns of the table.
 Each entity has a unique identifier known as primary key.
 Entities relate to one another using the keys, with foreign keys referencing
other entities.
 Operations on a relational database are carried out using the SQL language.
Django models

 Python is an object-oriented language.


 A Python object is a collection of data and methods.
 Classes are the blueprint for bundling data and functionality together.
 A Django model is a source of information about the behaviors of the data.
 Django framework provides a django.db.models.Model class that Python
classes can inherit.
 Each model maps to a single database table, where each attribute of the class
represents a database field.
 Creating a new instance of a model class in Django and saving it will create a
new row in the database.
Django models

 Django’s Object-Relational Mapping (ORM) bridges the relational model with


the object oriented paradigm.
 When the .save() method is called on a Django model object, the ORM
translates this operation into a SQL command that the database can
understand and sends this command to the database to store the data.
 ORM allows data interactions through objects.
 ORM minimizes the need of raw SQL and simplify the database operations.
 The database API through ORM ensures the project isn’t tightly bound to a
specific database, as ORM manages translations to the suitable database
engine.
 ORMs enhance security by promoting best practices and leveraging their
maturity in the field.
Creating the model

 Update model.py of the application.


 Creating the migration file:
 python manage.py makemigrations library
 Apply database changes
 python manage.py migrate
 By default, Django provides an auto-increment primary key named id for
every mode. This can be overridden by specifying a custom primary key.

Django’s database API

 The Django object-relational mapper (ORM) is a database abstraction API that


allows to create, retrieve, update, and delete objects.
 The ORM allows to generate SQL queries using the object-oriented paradigm
of Python.
 The Django ORM is based on QuerySets. A QuerySet is a collection of database
queries to retrieve objects from the database.
Django’s database API

 Creating Objects
 Run the command to open the Python shell:
 python manage.py shell

 from library.models import Book


 book = Book(title="Let Us Python", author="Aditya Kanetkar Yashavant Kanetkar",
isbn="9355515413")
 book.save()
 This action performs an Insert SQL statement. Here the object is created first and
then it is persisted to the database.
Django’s database API

 Creating objects
 Create the object and persist it to the database in a single operation:
 Book.objects.create(title="Django for Beginners", author="William S", isbn="978-
1735467207")

 Fetch an object from the database and create if it’s absent:


 book, created = Book.objects.get_or_create(title="Let Us Python", author="Aditya
Kanetkar Yashavant Kanetkar", isbn="9355515413")
Django’s database API

 Retrieving Objects
 Each Django model has at least one manager, and the default manager is called
objects.
 We get a QuerySet object using the model manager.
 To retrieve all objects from a table:
 all_books = Book.objects.all()
 all_books

 To retrieve the single object from the table:


 book = Book.objects.get(title="Let Us Python")
 Book
Django’s database API

 Filtering objects
 book = Book.objects.filter(author="William S")
 book
 View the SQL statement generated with this QuerySet:
 print(book.query)
Django’s database API

 Updating objects
 book = Book.objects.get(author="William S")
 book.author = "William S. Vincent"
 book.save()
 Deleting objects
 book = Book.objects.get(id=1)
 book
 book.delete()
Admin Portal

 Create Super User:


 python manage.py createsuperuser
 Follow the prompts to enter a username, email, and password.
 Update the application’s admin.py

 python manage.py runserver


 Navigate to http://127.0.0.1:8000/admin

You might also like