Web Development with Django - Second Edition

Book description

Create your own websites easily, securely, 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 that stand out from the crowd without spending hours on boilerplate code? You’ve made the right choice trusting the Django framework, and this book will tell you why. 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 will take you through all the essential concepts and help you explore its power to build real-world applications using Python.

Throughout the book, you’ll get the grips with the major features of Django 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 presented as exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. As you advance, you'll acquire 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. You’ll cover everyday tasks that are part of the development cycle of a real-world web application.

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

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
  • Build a RESTful API and JavaScript code that communicates with it
  • Connect to a database such as PostgreSQL

Who this book is for

This book is for programmers looking to enhance their web development skills using the Django framework. To fully understand the concepts explained in this book, basic knowledge of Python programming as well as familiarity with JavaScript, HTML, and CSS is assumed.

Table of contents

  1. Web Development with Django
  2. Contributors
  3. About the authors
  4. About the reviewer
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Download the color images
    6. Conventions used
    7. Get in touch
    8. Share Your Thoughts
    9. Download a free PDF copy of this book
  6. Chapter 1: An Introduction to Django
    1. Technical requirements
    2. Scaffolding a Django project and app
      1. Exercise 1.01 – creating a project and app, and starting the development server
    3. Understanding the model-view-template paradigm
      1. Models
      2. Views
      3. Templates
      4. MVT in practice
      5. An introduction to HTTP
      6. Processing a request
    4. Exploring the Django project structure
      1. The myproject directory
      2. Django development server
      3. Django apps
      4. PyCharm setup
      5. Exercise 1.02 – project setup in PyCharm
    5. Introducing Django views
    6. Exploring URL mapping detail
      1. Exercise 1.03 – writing a view and mapping a URL to it
    7. Working with GET, POST, and QueryDict objects
      1. Exercise 1.04 – exploring GET values and QueryDict objects
    8. Exploring Django settings
      1. Referring to Django Settings in Your Code
    9. Finding HTML templates in app directories
      1. Exercise 1.05 – creating a templates directory and a base template
      2. Rendering a template with the render function
      3. Exercise 1.06 – rendering a template in a view
      4. Rendering variables in templates
      5. Exercise 1.07 – using variables in templates
    10. Debugging and dealing with errors
      1. Exceptions
      2. Exercise 1.08 – generating and viewing exceptions
      3. Debugging
      4. Exercise 1.09 – debugging your code
    11. Activity 1.01 – creating a site welcome screen
    12. Activity 1.02 – a book search scaffold
    13. Summary
  7. Chapter 2: Models and Migrations
    1. Technical requirements
    2. Understanding and using 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. Understanding CRUD operations using SQL
      1. SQL create operations
      2. SQL read operations
      3. SQL update operations
      4. SQL delete Operations
    4. Exploring Django ORM
      1. Database configuration and creating Django applications
      2. Django apps
      3. Django migration
    5. Creating Django models and migrations
      1. Field options
      2. Primary keys
      3. Relationships
      4. Adding the Review model
      5. Model methods
      6. 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 the 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 using the exclude() method
      17. Retrieving objects using the order_by() method
      18. Querying across relationships
      19. Querying using foreign keys
      20. Querying using the model name
      21. Querying across foreign key relationships using the object instance
      22. Exercise 2.10 – querying across a many-to-many relationship using the 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
    7. Bulk create and bulk update operations
      1. Exercise 2.15 – creating multiple records using bulk_create
      2. Exercise 2.16 – updating multiple records using bulk_update
    8. Performing complex lookups using Q objects
      1. Exercise 2.17 – performing a complex query using a Q object
      2. Exercise 2.18 – verifying whether a queryset contains a given object
    9. Activity 2.01 – creating models for a project management application
    10. Populating the Bookr project’s database
    11. Summary
  8. Chapter 3: URL Mapping, Views, and Templates
    1. Technical requirements
    2. Understanding function-based views
    3. Understanding class-based views
    4. URL configuration
      1. Exercise 3.01 – implementing a simple function-based view
    5. Working with Django templates
      1. Exercise 3.02 – using templates to display a greeting message
      2. Django’s template language
      3. Exercise 3.03 – displaying a list of books and reviews
      4. Template inheritance
      5. Template styling with Bootstrap
      6. Exercise 3.04 – adding template inheritance and a Bootstrap navigation bar
      7. Activity 3.01 – implementing the book details view
    6. Summary
  9. Chapter 4: An Introduction to Django Admin
    1. Technical requirements
    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
    4. Managing Django users and groups
      1. Exercise 4.02 – adding and modifying users and groups through the admin app
    5. Registering models with the admin app
      1. Registering the reviews model
      2. Change lists
      3. The Change publisher page
      4. The Book change page
      5. Exercise 4.03 – foreign keys and deletion behavior in the admin app
    6. Customizing the admin interface
      1. Site-wide Django admin customizations
    7. Customizing the ModelAdmin classes
      1. The list display fields
      2. The display decorator
      3. The filter
      4. Exercise 4.04 – adding the date list_filter and date_hierarchy filters
      5. The search bar
      6. Excluding and grouping fields
      7. Activity 4.03 – customizing the Model admins
    8. Summary
  10. Chapter 5: Serving Static Files
    1. Technical requirements
    2. Static file serving
    3. Introduction to Static Files Finder
      1. Static file finders – use during a request
      2. AppDirectoriesFinder
      3. Static file namespacing
      4. Exercise 5.01 – serving a file from an app directory
    4. Generating static URLs with the static template tag
      1. Exercise 5.02 – using the static template tag
    5. FileSystemFinder
      1. Exercise 5.03 – serving from a project static directory
    6. Static file finders – use during collectstatic
      1. Exercise 5.04 – collecting static files for production
    7. STATICFILES_DIRS prefixed mode
    8. The findstatic command
      1. Exercise 5.05 – finding files using findstatic
    9. Serving the latest files (for cache invalidation)
      1. Exercise 5.06 – exploring the ManifestFilesStorage storage engine
    10. Custom storage engines
      1. Activity 5.01 – adding a Reviews logo
      2. Activity 5.02 – CSS enhancements
      3. Activity 5.03 – adding a global logo
    11. Summary
  11. Chapter 6: Forms
    1. Technical requirements
    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 or POST
      8. Why use GET when we can put parameters in the URL mappings?
    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
    5. Activity 1 – Book Search
    6. Summary
  12. Chapter 7: Advanced Form Validation and Model Forms
    1. Technical requirements
    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
    3. Adding placeholders and initial values
      1. Exercise 7.02 – placeholders and initial values
    4. Creating or editing Django models
      1. The ModelForm class
      2. Exercise 7.03 – creating and editing a publisher
      3. Activity 7.01 – styling and integrating the publisher form
      4. Activity 7.02 – Review Creation UI
    5. Summary
  13. Chapter 8: Media Serving and File Uploads
    1. Technical requirements
    2. Settings for media uploads and serving
      1. Serving media files in development
      2. Exercise 8.01 – configuring media storage and serving
      3. Context processors and using MEDIA_URL in templates
      4. Exercise 8.02 – template settings and using MEDIA_URL in templates
    3. File uploads using HTML forms
      1. Working with uploaded files in a view
      2. Exercise 8.03 – file upload and download
    4. File uploads with Django forms
      1. Exercise 8.04 – file uploads with a Django form
    5. Image uploads with Django forms
      1. Resizing an image with Pillow
      2. Exercise 8.05 – image uploads using Django forms
    6. Serving uploaded (and other) files using Django
      1. Storing files on model instances
      2. Storing images on model instances
      3. Working with FieldFile
      4. Referring to media in templates
    7. ModelForms and file uploads
      1. Exercise 8.07 – file and image uploads using ModelForm
      2. Handling file saving
    8. Activity 8.01 – image and PDF upload of books
    9. Activity 8.02 – displaying the cover and sample link
    10. Summary
  14. Chapter 9: Sessions and Authentication
    1. Technical requirements
    2. Middleware
      1. Middleware modules
      2. Implementing authentication views and templates
      3. Exercise 9.01 – repurposing the Admin app login template
    3. Password storage in Django
      1. The profile page and the request.user object
      2. Exercise 9.02 – adding a profile page
    4. Authentication decorators and redirection
      1. Exercise 9.03 – adding authentication decorators to the views
    5. Enhancing templates with authentication data
      1. Exercise 9.04 – toggling login and logout links in the base template
      2. Activity 9.01 – authentication-based content using conditional blocks in templates
    6. Sessions
      1. The session engine
      2. Do you need to flag cookie content?
      3. Pickle or JSON storage?
      4. Exercise 9.05 – examining the session key
      5. Storing data in sessions
      6. Exercise 9.06 – storing recently viewed books in sessions
      7. Activity 9.02 – using session storage for the Book Search page
    7. Summary
  15. Chapter 10: Advanced Django Admin and Customizations
    1. Technical requirements
    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 templates using template variables
      7. Activity 10.01 – building a custom admin dashboard with a built-in search
    4. Summary
  16. Chapter 11: Advanced Templating and Class-Based Views
    1. Technical requirements
    2. Template filters
    3. Custom template filters
      1. Creating custom template filters
      2. Implementing the custom filter function
      3. Using custom filters inside templates
      4. Exercise 11.01 – Creating a custom template filter
    4. String filters
    5. Template tags
      1. The types of template tags
      2. Simple tags
      3. Creating a simple template tag
      4. Exercise 11.02 – Creating a custom simple tag
      5. Inclusion tags
      6. Exercise 11.03 – Building a custom inclusion tag
    6. Django views
    7. Class-based views
      1. Exercise 11.04 – Creating a book catalog using a CBV
      2. CRUD operations with CBVs
      3. The Read view
      4. Activity 11.01 – Rendering details on the user profile page using inclusion tags
    8. Summary
  17. Chapter 12: Building a REST API
    1. Technical requirements
    2. Understanding REST APIs
    3. Django REST framework
      1. Installation and configuration
      2. Functional API views
    4. Understanding serializers
      1. Class-based API views and generic views
    5. Activity 12.01 – creating an API endpoint for a top contributors page
    6. Simplifying the code using ViewSets
      1. URL configuration using routers and Viewsets
      2. Exercise 12.04 – using ViewSets and routers
    7. Implementing authentication
      1. Token-based authentication
      2. Exercise 12.05 – omplementing token-based authentication for Bookr APIs
    8. Summary
  18. Chapter 13: Generating CSV, PDF, and Other Binary Files
    1. Technical requirements
    2. Working with CSV files inside Python
    3. Working with Python’s csv module
      1. Reading data from a CSV file
      2. Exercise 13.0 – 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
    4. Working with Excel files in Python
      1. Binary file formats for data exports
      2. Working with XLSX files using the XlsxWriter package
      3. XLSX files
      4. Exercise 13.03 – creating XLSX files in Python
    5. Working with PDF files in Python
      1. Converting web pages into PDFs
      2. Exercise 13.04 – generating a PDF version of a web page in Python
    6. Playing with graphs in Python
      1. Integrating plotly with Django
    7. Integrating visualizations with Django
      1. Exercise 13.06 – visualizing a user’s reading history on the user’s profile page
      2. Activity 13.01 – exporting the books read by a user as an XLSLX file
    8. Summary
  19. Chapter 14: Testing Your Django Applications
    1. Technical requirements
    2. 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
      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 RequestFactory
      1. Exercise 14.05 – using RequestFactory to test views
      2. Testing class-based views
    8. Test case classes in Django
      1. The SimpleTestCase class
      2. The TransactionTestCase class
      3. The LiveServerTestCase class
      4. Modularizing test code
    9. Activity 14.01 – testing models and views in Bookr
    10. Summary
  20. Chapter 15: Django Third-Party Libraries
    1. Technical requirements
    2. Environment variables
    3. django-configurations
      1. manage.py changes
      2. Configuration from environment variables
      3. Exercise 15.01 – Django configurations setup
    4. dj-database-url
      1. Exercise 15.02 – dj-database-url and setup
    5. The Django Debug Toolbar
      1. Exercise 15.03 – setting up the Django Debug Toolbar
    6. django-crispy-forms
      1. The crispy filter
      2. The crispy template Tag
      3. Exercise 15.04 – using Django Crispy Forms with SearchForm
    7. django-allauth
      1. django-allauth installation and setup
      2. Initiating authentication with django-allauth
      3. Other django-allauth features
      4. Activity 15.01 – using FormHelper to update forms
    8. Summary
  21. Chapter 16: Using a Frontend JavaScript Library with Django
    1. Technical requirements
    2. JavaScript frameworks
    3. An introduction to JavaScript
      1. Loading JavaScript
      2. Variables and constants
      3. Working with React
      4. Components
      5. Exercise 16.01 – setting up a React example
    4. JSX – a JavaScript syntax extension
      1. Exercise 16.02 – JSX and Babel
      2. JSX properties
      3. Exercise 16.03 – React component properties
      4. JavaScript promises
      5. The fetch function
      6. Exercise 16.04 – fetching and rendering books
    5. The verbatim template tag
      1. Activity 16.01 – reviews preview
    6. Summary
  22. Index
    1. Why subscribe?
  23. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share Your Thoughts
    3. Download a free PDF copy of this book

Product information

  • Title: Web Development with Django - Second Edition
  • Author(s): Ben Shaw, Saurabh Badhwar, Chris Guest, Bharath Chandra K S
  • Release date: May 2023
  • Publisher(s): Packt Publishing
  • ISBN: 9781803230603