Django PWD
Django PWD
Django PWD
Module Number: 05
Syllabus
2
Python Web Development_PWD1
Aim
This course aims to master Django's powerful features, including API development, leverage the
Django Admin app for seamless data management, and gain hands-on experience building full-stack
applications from scratch.
3
Python Web Development_PWD1
Objectives
The Objectives of this module are:
4
Python Web Development_PWD1
Outcome
• Understand the fundamental concepts of Django and utilization of the Django framework.
• Learn to create robust APIs and efficiently manage data through the Django Admin app.
• Acquire skills in designing and implementing Django views and templates, enabling you to
craft interactive user interfaces.
• Develop proficiency in adding, removing, and manipulating data using Django Forms and
Templating.
5
Python Web Development_PWD1
Contents
• Introduction to Django Web Application Framework
• Installing and Setting Up Django
• Django API
• Django Admin App
• Django Views
• Django Templates
• Add Remove Data
• Django Forms / Templating
• Building Some Full Stack Applications
• Conclusion
6
Python Web Development_PWD1
7
Python Web Development_PWD1
Model:
View:
• Processes user requests, interacts with the model, and returns appropriate responses.
8
Python Web Development_PWD1
Template:
• Manages the flow of data between the model and the view.
9
Python Web Development_PWD1
1. Rapid Development:
• Django follows the "Don't Repeat Yourself" (DRY) principle, enabling developers to write clean,
concise, and maintainable code.
• Provides built-in tools for common web development tasks, reducing the need for boilerplate code.
2. Scalability:
• Incorporates features like middleware, connection pooling, and caching for optimised performance.
10
Python Web Development_PWD1
• Developers can manage database records, user authentication, and other administrative tasks without
writing additional code.
• Supports various database backends, including PostgreSQL, MySQL, SQLite, and Oracle. 11
Python Web Development_PWD1
5. Security:
• Incorporates various security features by default, such as protection against SQL injection, cross-site
scripting (XSS), and cross-site request forgery (CSRF).
7. Versatility:
• Suitable for a wide range of web applications, from content management systems (CMS) to e-
commerce platforms and data-driven applications.
8. MVT Architecture:
13
Python Web Development_PWD1
14
Python Web Development_PWD1
Installing Django:
Before delving into Django development, the first step is to install the framework. Django can be easily
installed using Python's package manager, pip. Open your terminal or command prompt and execute the
following command:
15
Python Web Development_PWD1
Installing Django:
This command installs the latest version of Django. Once the installation is complete, you can verify it
by running:
This should display the installed Django version, confirming a successful installation.
16
Python Web Development_PWD1
Now that Django is installed, the next step is to create a Django project. A Django project is a collection
of settings and configurations for a specific web application. Follow these steps to create a new Django
project:
2. Navigate to the directory where you want to create your Django project.
17
Python Web Development_PWD1
Replace "projectname" with the desired name for your project. This command creates a new directory
with the specified project name, containing the necessary files and folders for a Django project.
18
Python Web Development_PWD1
A Django project is organised into a specific directory structure. Understanding this structure is crucial
for effective development. Here's an overview of the essential components:
1. projectname/:
2. manage.py:
A command-line utility for interacting with the project. Used for tasks like running development servers,
creating database tables, and more.
19
Python Web Development_PWD1
3. projectname/init.py:
An empty file that tells Python that this directory should be considered a Python package.
4. projectname/settings.py:
Configuration settings for the project. Includes database configuration, time zone settings, and more.
5. projectname/urls.py:
Contains the URL patterns for the project. Defines how URLs map to views.
20
Python Web Development_PWD1
Files for Asynchronous Server Gateway Interface (ASGI) and Web Server Gateway Interface (WSGI),
respectively. These are used for deploying Django applications to different server types.
7. projectname/static/:
8. projectname/media/:
21
Python Web Development_PWD1
9. projectname/templates/:
10. projectname/db.sqlite3:
The default SQLite database file. In production, you might use a different database backend.
If you are using a virtual environment (recommended), this directory contains the virtual environment
files.
22
Python Web Development_PWD1
Once you've created a Django project and understood its structure, you are ready to start building your
web application. Navigate into the project directory using the terminal and run the development server:
23
Python Web Development_PWD1
Django API
Django Models:
In Django, models define the structure of the database tables and encapsulate the business logic of the
application. Each model class corresponds to a database table, and each attribute of the model represents
a field in the table. Let's create a simple model to illustrate:
24
Python Web Development_PWD1
Django API
Django Models:
In this example, we've created a ‘Book’ model with attributes like ‘title’, ‘author’, and
‘publication_date’. The ‘__str__’ method provides a human-readable representation of the model
instances.
25
Python Web Development_PWD1
Django API
Once models are defined, Django makes it easy to create and update the corresponding database tables.
First, generate initial migrations using the following commands:
This command creates migration files based on the changes to the models. Next, apply migrations to
create or update the database tables:
This command executes the migration files and synchronises the database with the models.
26
Python Web Development_PWD1
Django API
• Creating Records:
27
Python Web Development_PWD1
Django API
• Querying Records:
• Filtering Records:
28
Python Web Development_PWD1
Django API
• Updating Records:
• Deleting Records:
These operations demonstrate the simplicity and readability of Django's ORM for database interactions.
29
Python Web Development_PWD1
Django API
Django uses URL patterns to map URLs to views, allowing for dynamic and organised routing within a
web application. URL patterns are defined in the ‘urls.py’ file of your Django app. Let's create a basic
example:
In this example, the ‘path’ function associates URLs with corresponding views. The ‘<int:book_id>’
part captures an integer parameter from the URL, which can be passed to the ‘book_detail’ view.
30
Python Web Development_PWD1
Django API
Understanding Django models, databases, ORM, and URL patterns is fundamental for building dynamic
web applications. Models define data structures, migrations manage database changes, the ORM
simplifies database interactions, and URL patterns organise routing. These components work together to
create a robust and scalable web application using the Django framework.
31
Python Web Development_PWD1
Django comes with a built-in admin app that provides a powerful and customisable interface for
managing the application's data. Setting up the Django admin involves a few straightforward steps.
32
Python Web Development_PWD1
33
Python Web Development_PWD1
Access the admin site at ‘http://localhost:8000/admin/’ and log in with the superuser credentials.
34
Python Web Development_PWD1
Django admin is highly customisable to suit the specific needs of your application. Customisations can
be applied by creating an ‘admin.py’ file within each app and defining admin classes.
Registering Models:
In the ‘admin.py’ file, register the models you want to manage in the admin interface:
35
Python Web Development_PWD1
To customise the way a model is displayed in the admin interface, create a class that inherits from
‘admin.ModelAdmin’:
This example configures the list view with specific fields, filters, and search capabilities.
36
Python Web Development_PWD1
If your model has related models, you can use inline models to edit them within the same admin page:
37
Python Web Development_PWD1
Once the Django admin is set up and customized, managing database records becomes a straightforward
process.
1. Create Records:
• Click on the model and use the "Add" button to create new records.
38
Python Web Development_PWD1
2. Update Records:
3. Delete Records:
• Apply filters in the right sidebar to narrow down records based on certain criteria.
5. Batch Actions:
The Django admin app streamlines the process of managing database records, making it accessible and
efficient for administrators and developers. 40
Python Web Development_PWD1
The Django admin app is a powerful tool for managing database records, and its flexibility allows
developers to tailor it to the specific requirements of their applications. By following the steps to set up
the admin site, customising the interface, and understanding record management, developers can
leverage the Django admin to streamline administrative tasks and focus on building core application
features.
41
Python Web Development_PWD1
Django Views
In the Django web framework, a view is responsible for processing user requests and returning an
appropriate response. Views encapsulate the logic that defines how data is retrieved, processed, and
presented to the user. Django supports two primary approaches to defining views: function-based views
(FBVs) and class-based views (CBVs).
42
Python Web Development_PWD1
Django Views
Function-based views are the traditional way of defining views in Django. A function-based view is a
Python function that takes a web request as its first argument and returns an HTTP response. Here's an
example of a simple function-based view:
In this example, the ‘hello_world’ function is a basic view that returns a simple "Hello, World!"
message as an HTTP response.
43
Python Web Development_PWD1
Django Views
Class-based views provide a more organised and reusable way to structure view logic. CBVs are based
on Python classes, where each class inherits from a Django-provided class. Here's an equivalent
example using a class-based view:
In this example, the ‘HelloWorldView’ class inherits from Django's ‘View’ class, and the ‘get’ method
handles HTTP GET requests.
44
Python Web Development_PWD1
Django Views
Both Function-Based Views (FBVs) and Class-Based Views (CBVs) have their advantages, and the
choice between them often comes down to personal preference and the complexity of the view logic.
45
Python Web Development_PWD1
Django Views
In Django, URL routing is the process of mapping URLs to specific view functions or classes. This is typically
defined in the ‘urls.py’ file within each Django app. Let's illustrate URL routing using the previously defined views:
In this example, the ‘path’ function in the ‘urlpatterns’ list associates the URL path 'hello/' with the ‘hello_world’
function-based view.
46
Python Web Development_PWD1
Django Views
For class-based views, the as_view() method is used to convert the class into a function-like object that can be used
in URL patterns.
47
Python Web Development_PWD1
Django Views
Django views serve as the core logic for handling HTTP requests and generating responses in web
applications. Whether using function-based views or class-based views, Django provides flexibility in
structuring and organising view logic. URL routing connects specific URLs to their corresponding
views, allowing developers to create a well-structured and navigable web application. Understanding
these concepts is fundamental to creating dynamic and interactive web applications using the Django
framework.
48
Python Web Development_PWD1
Django Templates
Django templates are a powerful tool for generating dynamic HTML content in web applications. They allow
developers to embed Python-like code within HTML, facilitating the rendering of dynamic content based on data
passed from views. Let's delve into the creation of Django templates with a basic example:
In this example, ‘{{ name }}’ is a template variable that will be replaced with actual data when rendering the
template. 49