You are on page 1of 49

Subject Name: Computer Science

Module Number: 05

Module Name: Python Web Development_PWD1


Python Web Development_PWD1

Syllabus

Python Web Development


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

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:

• Understand the fundamentals of web development by mastering Django.


• Learn to create dynamic and interactive web applications using Django Templates and Forms.
• Acquire the skills to build comprehensive full-stack applications.
• Develop a solid foundation in Django's templating system, empowering you to create user-
friendly interfaces.

4
Python Web Development_PWD1

Outcome

At the end of this module, you are expected to:

• 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

Introduction to Django Web Application Framework


Overview of Django:

Django is a high-level, open-source web application framework written in Python. It


follows the Model-View-Controller (MVC) architectural pattern, with a slight
variation known as the Model-View-Template (MVT) pattern. Django's primary goal
is to simplify the process of building robust, scalable, and maintainable web
applications by providing a clean and pragmatic design.

7
Python Web Development_PWD1

Introduction to Django Web Application Framework


Core Components of Django:

Model:

• Represents the data structure and business logic of the application.

• Uses Object-Relational Mapping (ORM) to interact with databases.

View:

• Handles the presentation layer and user interface.

• Processes user requests, interacts with the model, and returns appropriate responses.

8
Python Web Development_PWD1

Introduction to Django Web Application Framework


Core Components of Django:

Template:

• Defines the structure and layout of the HTML pages.

• Allows embedding dynamic content using Django template language.

Controller (or, in Django's case, the URLconf):

• Manages the flow of data between the model and the view.

• Defines the URL patterns and their corresponding view functions.

9
Python Web Development_PWD1

Introduction to Django Web Application Framework

Key Features and Advantages:

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:

• Designed to scale seamlessly from small projects to large, high-traffic websites.

• Incorporates features like middleware, connection pooling, and caching for optimised performance.

10
Python Web Development_PWD1

Introduction to Django Web Application Framework

Key Features and Advantages:

3. Built-in Admin Interface:

• Django includes a powerful and customisable administrative interface.

• Developers can manage database records, user authentication, and other administrative tasks without
writing additional code.

4. ORM for Database Interaction:

• Django's Object-Relational Mapping simplifies database interaction by allowing developers to work


with database records using Python objects.

• Supports various database backends, including PostgreSQL, MySQL, SQLite, and Oracle. 11
Python Web Development_PWD1

Introduction to Django Web Application Framework

Key Features and Advantages:

5. Security:

• Incorporates various security features by default, such as protection against SQL injection, cross-site
scripting (XSS), and cross-site request forgery (CSRF).

• Encourages best practices for secure coding.

6. Community and Documentation:

• Django has a vibrant and supportive community of developers.

• Comprehensive documentation and a plethora of third-party packages contribute to the framework's


robust ecosystem. 12
Python Web Development_PWD1

Introduction to Django Web Application Framework

Key Features and Advantages:

7. Versatility:

• Suitable for a wide range of web applications, from content management systems (CMS) to e-
commerce platforms and data-driven applications.

• Offers flexibility in choosing components and integrating with other technologies.

8. MVT Architecture:

• Django's Model-View-Template architecture simplifies the separation of concerns, making it easier to


understand, maintain, and extend code.

13
Python Web Development_PWD1

Introduction to Django Web Application Framework

Key Features and Advantages:

9. Open Source and Free:

• Released under the BSD licence, making it free and open-source.

• Allows developers to customise and contribute to the framework's continuous improvement.

In summary, Django empowers developers to focus on building feature-rich web applications by


providing a well-structured framework, a set of robust tools, and an active community. Its versatility,
scalability, and emphasis on best practices make it a popular choice for developers aiming to deliver
high-quality web solutions efficiently.

14
Python Web Development_PWD1

Installing and Setting Up Django

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 and Setting Up Django

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

Installing and Setting Up Django

Creating a Django Project:

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:

1. Open your terminal or command prompt.

2. Navigate to the directory where you want to create your Django project.

17
Python Web Development_PWD1

Installing and Setting Up Django

Creating a Django Project:

Run the following command:

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

Installing and Setting Up Django

Understanding Project Structure:

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/:

The main project directory.

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

Installing and Setting Up Django

Understanding Project Structure:

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

Installing and Setting Up Django

Understanding Project Structure:

6. projectname/asgi.py and projectname/wsgi.py:

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/:

A directory to store static files like CSS, JavaScript, and images.

8. projectname/media/:

A directory to store user-uploaded files.

21
Python Web Development_PWD1

Installing and Setting Up Django

Understanding Project Structure:

9. projectname/templates/:

A directory to store HTML templates used by the application.

10. projectname/db.sqlite3:

The default SQLite database file. In production, you might use a different database backend.

11. venv/ (Optional):

If you are using a virtual environment (recommended), this directory contains the virtual environment
files.

22
Python Web Development_PWD1

Installing and Setting Up Django

Understanding Project Structure:

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

Creating and Migrating Databases:

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

Querying the Database with Django ORM:

Django's Object-Relational Mapping (ORM) simplifies database queries by allowing developers to


interact with the database using Python code. Here are some common query operations:

• Creating Records:

27
Python Web Development_PWD1

Django API

Querying the Database with Django ORM:

• Querying Records:

• Filtering Records:

28
Python Web Development_PWD1

Django API

Querying the Database with Django ORM:

• 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 URL Patterns:

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 Admin App

Setting Up Django Admin:

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.

Enabling Admin Site:

1. Ensure 'django.contrib.admin' is included in the ‘INSTALLED_APPS’ list in your project's


‘settings.py’:

32
Python Web Development_PWD1

Django Admin App

Setting Up Django Admin:

2. Run the following command to apply the necessary migrations:

3. Create a superuser account to access the admin site:

Follow the prompts to set a username, email, and password.

33
Python Web Development_PWD1

Django Admin App

Setting Up Django Admin:

4. Run the development server:

Access the admin site at ‘http://localhost:8000/admin/’ and log in with the superuser credentials.

34
Python Web Development_PWD1

Django Admin App

Customising the Admin Interface:

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

Django Admin App

Customising the Admin Interface:

Customising Model Admin:

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

Django Admin App

Customising the Admin Interface:

Adding Inline Models:

If your model has related models, you can use inline models to edit them within the same admin page:

37
Python Web Development_PWD1

Django Admin App

Customising the Admin Interface:

Managing Database Records:

Once the Django admin is set up and customized, managing database records becomes a straightforward
process.

1. Create Records:

• Log in to the admin site.

• Navigate to the app containing the model you want to manage.

• Click on the model and use the "Add" button to create new records.

38
Python Web Development_PWD1

Django Admin App

Customising the Admin Interface:

Managing Database Records:

2. Update Records:

• In the list view, click on the record you want to update.

• Modify the fields in the edit form and save.

3. Delete Records:

• In the list view, select the records you want to delete.

• Use the "Action" dropdown to choose "Delete selected items."


39
Python Web Development_PWD1

Django Admin App

Customising the Admin Interface:

Managing Database Records:

4. Search and Filter:

• Use the search bar to find specific records.

• Apply filters in the right sidebar to narrow down records based on certain criteria.

5. Batch Actions:

• Perform batch actions on selected records using the "Action" dropdown.

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

Django Admin App

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

Introduction to 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

Class-Based Views vs Function-Based Views:

Function-Based Views (FBVs):

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 (CBVs):

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

Class-Based Views vs Function-Based 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

URL Routing and View Functions:

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:

Function-Based View URL Routing:

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

URL Routing and View Functions:

Class-Based View URL Routing:

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

Creating 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

You might also like