Web Development with Django

Book description

Learn how to create your own websites simply, safely, and quickly with Django by tackling practical activities based on realistic case studies

Key Features

  • Understand Django functionality and the Model-View-Template (MVT) paradigm
  • Create and iteratively build a book review website, adding features as you build your knowledge
  • Explore advanced concepts such as REST API implementation and third-party module integration

Book Description

Do you want to develop reliable and secure applications which stand out from the crowd, rather than spending hours on boilerplate code? Then the Django framework is where you should begin. Often referred to as a 'batteries included' web development framework, Django comes with all the core features needed to build a standalone application.

Web Development with Django takes this philosophy and equips you with the knowledge and confidence to build real-world applications using Python.

Starting with the essential concepts of Django, you'll cover its major features by building a website called Bookr – a repository for book reviews. This end-to-end case study is split into a series of bitesize projects that are presented as exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way.

As you progress, you'll learn various practical skills, including how to serve static files to add CSS, JavaScript, and images to your application, how to implement forms to accept user input, and how to manage sessions to ensure a reliable user experience. Throughout this book, you'll cover key daily tasks that are part of the development cycle of a real-world web application.

By the end of this book, you'll have the skills and confidence to creatively tackle your own ambitious projects with Django.

What you will learn

  • Create a new application and add models to describe your data
  • Use views and templates to control behavior and appearance
  • Implement access control through authentication and permissions
  • Develop practical web forms to add features such as file uploads
  • Develop a RESTful API and JavaScript code that communicates with it
  • Connect to a database such as PostgreSQL

Who this book is for

Web Development with Django is designed for programmers who want to gain web development skills with the Django framework. To fully understand the concepts explained in this book, you must have basic knowledge of Python programming, as well as familiarity with JavaScript, HTML, and CSS.

Table of contents

  1. Web Development with Django
  2. Preface
    1. About the Book
      1. About the Authors
      2. Who This Book Is For
      3. About the Chapters
      4. Conventions
      5. Before You Begin
      6. Installing Python
      7. Installing PyCharm Community Edition
      8. virtualenv
      9. Installing Django
      10. Django 3.0 and Django 3.1
      11. DB Browser for SQLite
      12. Installing on Windows
      13. Installing on macOS
      14. Installing on Linux
      15. Using DB Browser
      16. The Bookr Project
      17. The Final Directory
      18. Populating the Data
      19. Installing the Code Bundle
      20. Get in Touch
      21. Please Leave a Review
  3. 1. Introduction to Django
    1. Introduction
    2. Scaffolding a Django Project and App
      1. Exercise 1.01: Creating a Project and App, and Starting the Dev Server
    3. Model View Template
      1. Models
      2. Views
      3. Templates
        1. MVT in Practice
      4. Introduction to HTTP
      5. Processing a Request
      6. Django Project
        1. The myproject Directory
        2. Django Development Server
      7. Django Apps
      8. PyCharm Setup
      9. Exercise 1.02: Project Setup in PyCharm
      10. View Details
      11. URL Mapping Detail
      12. Exercise 1.03: Writing a View and Mapping a URL to It
      13. GET, POST, and QueryDict Objects
      14. Exercise 1.04: Exploring GET Values and QueryDict
      15. Exploring Django Settings
        1. Using Settings in Your Code
      16. Finding HTML Templates in App Directories
      17. Exercise 1.05: Creating a Templates Directory and a Base Template
      18. Rendering a Template with the render Function
      19. Exercise 1.06: Rendering a Template in a View
      20. Rendering Variables in Templates
      21. Exercise 1.07: Using Variables in Templates
      22. Debugging and Dealing with Errors
      23. Exceptions
      24. Exercise 1.08: Generating and Viewing Exceptions
      25. Debugging
      26. Exercise 1.09: Debugging Your Code
      27. Activity 1.01: Creating a Site Welcome Screen
      28. Activity 1.02: Book Search Scaffold
    4. Summary
  4. 2. Models and Migrations
    1. Introduction
    2. Databases
      1. Relational Databases
      2. Non-Relational Databases
      3. Database Operations Using SQL
      4. Data Types in Relational databases
      5. Exercise 2.01: Creating a Book Database
    3. SQL CRUD Operations
      1. SQL Create Operations
      2. SQL Read Operations
      3. SQL Update Operations
      4. SQL Delete Operations
      5. Django ORM
      6. Database Configuration and Creating Django Applications
      7. Django Apps
      8. Django Migration
      9. Creating Django Models and Migrations
      10. Field Types
      11. Field Options
      12. Primary Keys
    4. Relationships
      1. Many to One
    5. Many to Many
      1. One-to-One Relationships
      2. Adding the Review Model
      3. Model Methods
      4. Migrating the Reviews App
    6. Django's Database CRUD Operations
      1. Exercise 2.02: Creating an Entry in the Bookr Database
      2. Exercise 2.03: Using the create() Method to Create an Entry
      3. Creating an Object with a Foreign Key
      4. Exercise 2.04: Creating Records for a Many-to-One Relationship
      5. Exercise 2.05: Creating Records with Many-to-Many Relationships
      6. Exercise 2.06: A Many-to-Many Relationship Using the add() Method
      7. Using create() and set() Methods for Many-to-Many Relationships
      8. Read Operations
      9. Exercise 2.07: Using the get() Method to Retrieve an Object
      10. Returning an Object Using the get() Method
      11. Exercise 2.08: Using the all() Method to Retrieve a Set of Objects
      12. Retrieving Objects by Filtering
      13. Exercise 2.09: Using the filter() Method to Retrieve Objects
      14. Filtering by Field Lookups
      15. Using Pattern Matching for Filtering Operations
      16. Retrieving Objects by Excluding
      17. Retrieving Objects Using the order_by() Method
      18. Querying Across Relationships
      19. Querying Using Foreign Keys
      20. Querying Using Model Name
      21. Querying Across Foreign Key Relationships Using the Object Instance
      22. Exercise 2.10: Querying Across a Many-to-Many Relationship Using Field Lookup
      23. Exercise 2.11: A Many-to-Many Query Using Objects
      24. Exercise 2.12: A Many-to-Many Query Using the set() Method
      25. Exercise 2.13: Using the update() Method
      26. Exercise 2.14: Using the delete() Method
      27. Activity 2.01: Create Models for a Project Management Application
      28. Populating the Bookr Project's Database
    7. Summary
  5. 3. URL Mapping, Views, and Templates
    1. Introduction
    2. Function-Based Views
    3. Class-Based Views
    4. URL Configuration
      1. Exercise 3.01: Implementing a Simple Function-Based View
    5. Templates
      1. Exercise 3.02: Using Templates to Display a Greeting Message
    6. Django Template Language
      1. Template Variables
        1. Template Tags
        2. Comments
        3. Filters
      2. Exercise 3.03: Displaying a List of Books and Reviews
      3. Template Inheritance
      4. Template Styling with Bootstrap
      5. Exercise 3.04: Adding Template Inheritance and a Bootstrap Navigation Bar
      6. Activity 3.01: Implement the Book Details View
    7. Summary
  6. 4. Introduction to Django Admin
    1. Introduction
    2. Creating a Superuser Account
      1. Exercise 4.01: Creating a Superuser Account
    3. CRUD Operations Using the Django Admin App
      1. Create
      2. Retrieve
      3. Update
      4. Delete
      5. Users and Groups
      6. Exercise 4.02: Adding and Modifying Users and Groups through the Admin app
    4. Registering the Reviews Model
      1. Change Lists
      2. The Publisher Change Page
      3. The Book Change Page
      4. Exercise 4.03: Foreign Keys and Deletion Behavior in the Admin App
    5. Customizing the Admin Interface
      1. Site-Wide Django Admin Customizations
      2. Examining the AdminSite object from the Python Shell
        1. Subclassing AdminSite
      3. Activity 4.01: Customizing the SiteAdmin
      4. Customizing the ModelAdmin Classes
        1. The List Display Fields
        2. The Filter
      5. Exercise 4.04: Adding a Date list_filter and date_hierarchy
      6. The Search Bar
      7. Excluding and Grouping Fields
      8. Activity 4.02: Customizing the Model Admins
    6. Summary
  7. 5. Serving Static Files
    1. Introduction
    2. Static File Serving
      1. Introduction to Static File Finders
      2. Static File Finders: Use During a Request
      3. AppDirectoriesFinder
      4. Static File Namespacing
      5. Exercise 5.01: Serving a File from an App Directory
      6. Generating Static URLs with the static Template Tag
      7. Exercise 5.02: Using the static Template Tag
      8. FileSystemFinder
      9. Exercise 5.03: Serving from a Project static Directory
      10. Static File Finders: Use During collectstatic
      11. Exercise 5.04: Collecting Static Files for Production
      12. STATICFILES_DIRS Prefixed Mode
      13. The findstatic Command
      14. Exercise 5.05: Finding Files Using findstatic
      15. Serving the Latest Files (for Cache Invalidation)
      16. Exercise 5.06: Exploring the ManifestFilesStorage Storage Engine
      17. Custom Storage Engines
      18. Activity 5.01: Adding a reviews Logo
      19. Activity 5.02: CSS Enhancements
      20. Activity 5.03: Adding a Global Logo
    3. Summary
  8. 6. Forms
    1. Introduction
    2. What Is a Form?
      1. The <form> Element
      2. Types of Inputs
      3. Exercise 6.01: Building a Form in HTML
      4. Form Security with Cross-Site Request Forgery Protection
      5. Accessing Data in the View
      6. Exercise 6.02: Working with POST Data in a View
      7. Choosing between GET and POST
      8. Why Use GET When We Can Put Parameters in the URL?
    3. The Django Forms Library
      1. Defining a Form
      2. Rendering a Form in a Template
      3. Exercise 6.03: Building and Rendering a Django Form
    4. Validating Forms and Retrieving Python Values
      1. Exercise 6.04: Validating Forms in a View
      2. Built-In Field Validation
      3. Exercise 6.05: Adding Extra Field Validation
      4. Activity 6.01: Book Searching
    5. Summary
  9. 7. Advanced Form Validation and Model Forms
    1. Introduction
    2. Custom Field Validation and Cleaning
      1. Custom Validators
      2. Cleaning Methods
      3. Multi-Field Validation
      4. Exercise 7.01: Custom Clean and Validation Methods
      5. Placeholders and Initial Values
      6. Exercise 7.02: Placeholders and Initial Values
      7. Creating or Editing Django Models
      8. The ModelForm Class
      9. Exercise 7.03: Creating and Editing a Publisher
      10. Activity 7.01: Styling and Integrating the Publisher Form
      11. Activity 7.02: Review Creation UI
    3. Summary
  10. 8. Media Serving and File Uploads
    1. Introduction
    2. Settings for Media Uploads and Serving
      1. Serving Media Files in Development
      2. Exercise 8.01: Configuring Media Storage and Serving Media Files
    3. Context Processors and Using MEDIA_URL in Templates
      1. Exercise 8.02: Template Settings and Using MEDIA_URL in Templates
    4. File Uploads Using HTML Forms
      1. Working with Uploaded Files in a View
        1. Security and Trust of Browsers' Sent Values
      2. Exercise 8.03: File Upload and Download
      3. File Uploads with Django Forms
      4. Exercise 8.04: File Uploads with a Django Form
      5. Image Uploads with Django Forms
      6. Resizing an Image with Pillow
      7. Exercise 8.05: Image Uploads using Django Forms
      8. Serving Uploaded (and Other) Files Using Django
    5. Storing Files on Model Instances
      1. Storing Images on Model Instances
      2. Working with FieldFile
        1. Custom Storage Engines
        2. Reading a Stored FieldFile
        3. Storing Existing Files or Content in FileField
        4. Writing PIL Images to ImageField
      3. Referring to Media in Templates
      4. Exercise 8.06: FileField and ImageField on Models
      5. ModelForms and File Uploads
      6. Exercise 8.07: File and Image Uploads Using a ModelForm
      7. Activity 8.01: Image and PDF Uploads of Books
      8. Activity 8.02: Displaying Cover and Sample Links
    6. Summary
  11. 9. Sessions and Authentication
    1. Introduction
    2. Middleware
      1. Middleware Modules
      2. Implementing Authentication Views and Templates
      3. Exercise 9.01: Repurposing the Admin App Login Template
      4. Password Storage in Django
      5. The Profile Page and the request.user Object
      6. Exercise 9.02: Adding a Profile Page
      7. Authentication Decorators and Redirection
      8. Exercise 9.03: Adding Authentication Decorators to the Views
      9. Enhancing Templates with Authentication Data
      10. Exercise 9.04: Toggling Login and Logout Links in the Base Template
      11. Activity 9.01: Authentication-Based Content Using Conditional Blocks in Templates
    3. Sessions
      1. The Session Engine
        1. Do You Need to Flag Cookie Content?
      2. Pickle or JSON storage
      3. Exercise 9.05: Examining the Session Key
      4. Storing Data in Sessions
      5. Exercise 9.06: Storing Recently Viewed Books in Sessions
      6. Activity 9.02: Using Session Storage for the Book Search Page
    4. Summary
  12. 10. Advanced Django Admin and Customizations
    1. Introduction
    2. Customizing the Admin Site
      1. Discovering Admin Files in Django
      2. Django's AdminSite Class
      3. Exercise 10.01: Creating a Custom Admin Site for Bookr
      4. Overriding the Default admin.site
      5. Exercise 10.02: Overriding the Default Admin Site
      6. Customizing Admin Site Text Using AdminSite Attributes
      7. Customizing Admin Site Templates
      8. Exercise 10.03: Customizing the Logout Template for the Bookr Admin Site
    3. Adding Views to the Admin Site
      1. Creating the View Function
      2. Accessing Common Template Variables
      3. Mapping URLs for the Custom View
      4. Restricting Custom Views to the Admin Site
      5. Exercise 10.04: Adding Custom Views to the Admin Site
      6. Passing Additional Keys to the Templates Using Template Variables
      7. Activity 10.01: Building a Custom Admin Dashboard with Built-In Search
    4. Summary
  13. 11. Advanced Templating and Class-Based Views
    1. Introduction
    2. Template Filters
    3. Custom Template Filters
      1. Template Filters
      2. Setting Up the Directory for Storing Template Filters
      3. Setting Up the Template Library
      4. Implementing the Custom Filter Function
      5. Using Custom Filters inside Templates
      6. Exercise 11.01: Creating a Custom Template Filter
      7. String Filters
    4. Template Tags
      1. Types of Template Tags
      2. Simple Tags
      3. How to Create a Simple Template Tag
        1. Setting Up the Directory
        2. Setting Up the Template Library
        3. Implementing a Simple Template Tag
        4. Using Simple Tags inside Templates
      4. Exercise 11.02: Creating a Custom Simple Tag
        1. Passing the Template Context in a Custom Template Tag
      5. Inclusion Tags
        1. Implementing Inclusion Tags
        2. Using an Inclusion Tag inside a Template
      6. Exercise 11.03: Building a Custom Inclusion Tag
    5. Django Views
    6. Class-Based Views
      1. Exercise 11.04: Creating a Book Catalog Using a CBV
      2. CRUD Operations with CBVs
        1. Create View
      3. Update View
        1. Delete View
      4. Read View
      5. Activity 11.01: Rendering Details on the User Profile Page Using Inclusion Tags
    7. Summary
  14. 12. Building a REST API
    1. Introduction
    2. REST APIs
      1. Django REST Framework
      2. Installation and Configuration
      3. Functional API Views
      4. Exercise 12.01: Creating a Simple REST API
    3. Serializers
      1. Exercise 12.02: Creating an API View to Display a List of Books
      2. Class-Based API Views and Generic Views
      3. Model Serializers
      4. Exercise 12.03: Creating Class-Based API Views and Model Serializers
      5. Activity 12.01: Creating an API Endpoint for a Top Contributors Page
    4. ViewSets
    5. Routers
      1. Exercise 12.04: Using ViewSets and Routers
    6. Authentication
      1. Token-Based Authentication
      2. Exercise 12.05: Implementing Token-Based Authentication for Bookr APIs
    7. Summary
  15. 13. Generating CSV, PDF, and Other Binary Files
    1. Introduction
      1. Working with CSV Files inside Python
    2. Working with Python's CSV Module
      1. Reading Data from a CSV File
      2. Exercise 13.01: Reading a CSV File with Python
      3. Writing to CSV Files Using Python
      4. Exercise 13.02: Generating a CSV File Using Python's csv Module
      5. A Better Way to Read and Write CSV Files
    3. Working with Excel Files in Python
      1. Binary File Formats for Data Exports
      2. Working with XLSX Files Using the XlsxWriter Package
        1. XLSX Files
        2. The XlsxWriter Python Package
        3. Creating a Workbook
        4. Creating a Worksheet
        5. Writing Data to the Worksheet
        6. Writing the Data to the Workbook
      3. Exercise 13.03: Creating XLSX Files in Python
    4. Working with PDF Files in Python
      1. Converting Web Pages to PDFs
      2. Exercise 13.04: Generating a PDF Version of a Web Page in Python
    5. Playing with Graphs in Python
      1. Generating Graphs with plotly
        1. Setting Up a Figure
        2. Generating a Plot
        3. Rendering a Plot on a Web Page
      2. Exercise 13.05: Generating Graphs in Python
      3. Integrating plotly with Django
    6. Integrating Visualizations with Django
      1. Exercise 13.06: Visualizing a User's Reading History on the User Profile Page
      2. Activity 13.01: Exporting the Books Read by a User as an XLSLX File
    7. Summary
  16. 14. Testing
    1. Introduction
    2. The Importance of Testing
    3. Automation Testing
    4. Testing in Django
      1. Implementing Test Cases
      2. Unit Testing in Django
      3. Utilizing Assertions
      4. Exercise 14.01: Writing a Simple Unit Test
        1. Types of Assertions
      5. Performing Pre-Test Setup and Cleanup after Every Test Case Run
    5. Testing Django Models
      1. Exercise 14.02: Testing Django Models
    6. Testing Django Views
      1. Exercise 14.03: Writing Unit Tests for Django Views
      2. Testing Views with Authentication
      3. Exercise 14.04: Writing Test Cases to Validate Authenticated Users
    7. Django Request Factory
      1. Exercise 14.05: Using a Request Factory to Test Views
      2. Testing Class-Based Views
    8. Test Case Classes in Django
      1. SimpleTestCase
      2. TransactionTestCase
      3. LiveServerTestCase
      4. Modularizing Test Code
      5. Activity 14.01: Testing Models and Views in Bookr
    9. Summary
  17. 15. Django Third-Party Libraries
    1. Introduction
      1. Environment Variables
      2. django-configurations
      3. manage.py changes
      4. Configuration from Environment Variables
      5. Exercise 15.01: Django Configurations Setup
      6. dj-database-url
      7. Exercise 15.02: dj-database-url and Setup
      8. The Django Debug Toolbar
      9. Exercise 15.03: Setting Up the Django Debug Toolbar
    2. django-crispy-forms
      1. The crispy Filter
      2. The crispy Template Tag
      3. Exercise 15.04: Using Django Crispy Forms with the SearchForm
      4. django-allauth
        1. django-allauth Installation and Setup
        2. GitHub Auth Setup
        3. Google Auth Setup
      5. Initiating Authentication with django-allauth
        1. Other django-allauth Features
      6. Activity 15.01: Using FormHelper to Update Forms
    3. Summary
  18. 16. Using a Frontend JavaScript Library with Django
    1. Introduction
    2. JavaScript Frameworks
    3. JavaScript Introduction
      1. React
      2. Components
      3. Exercise 16.01: Setting Up a React Example
      4. JSX
      5. Exercise 16.02: JSX and Babel
      6. JSX Properties
      7. Exercise 16.03: React Component Properties
      8. JavaScript Promises
      9. fetch
        1. The JavaScript map Method
      10. Exercise 16.04: Fetching and Rendering Books
      11. The verbatim Template Tag
      12. Activity 16.01: Reviews Preview
    4. Summary

Product information

  • Title: Web Development with Django
  • Author(s): Ben Shaw, Saurabh Badhwar, Andrew Bird, Bharath Chandra K S, Chris Guest
  • Release date: February 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781839212505