E-Note 24867 Content Document 20240927094010AM
E-Note 24867 Content Document 20240927094010AM
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
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
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
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
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
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
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
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
Creating Objects
Run the command to open the Python shell:
python manage.py shell
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")
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
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