Django 4 By Example - Fourth Edition

Book description

Learn to create fully functional web applications with authentication, content management systems, payment processing, RESTful APIs, and more Purchase of the print or Kindle book includes a free eBook in PDF format.

Key Features

  • Implement advanced functionalities, such as full-text search engines, user activity streams, payment gateways, and recommendation engines
  • Integrate JavaScript, PostgreSQL, Redis, Celery, and Memcached into your applications
  • Add real-time features with Django Channels and WebSockets

Book Description

Django 4 By Example is the 4th edition of the best-selling franchise that helps you build web apps. This book will walk you through the creation of real-world applications, solving common problems, and implementing best practices using a step-by-step approach.

You'll cover a wide range of web app development topics as you build four different apps:

A blog application: Create data models, views, and URLs and implement an admin site for your blog. Create sitemaps and RSS feeds and implement a full-text search engine with PostgreSQL.

A social website: Implement authentication with Facebook, Twitter, and Google. Create user profiles, image thumbnails, a bookmarklet, and an activity stream. Implement a user follower system and add infinite scroll pagination to your website.

An e-commerce application: Build a product catalog, a shopping cart, and asynchronous tasks with Celery and RabbitMQ. Process payments with Stripe and manage payment notifications via webhooks. Build a product recommendation engine with Redis. Create PDF invoices and export orders to CSV.

An e-learning platform: Create a content management system to manage polymorphic content. Cache content with Memcached and Redis. Build and consume a RESTful API. Implement a real-time chat using WebSockets with ASGI. Create a production environment using NGINX, uWSGI and Daphne with Docker Compose.

This is a practical book that will have you creating web apps quickly.

What you will learn

  • Learn Django essentials, including models, ORM, views, templates, URLs, forms, authentication, signals and middleware
  • Implement different modules of the Django framework to solve specific problems
  • Integrate third-party Django applications into your project
  • Build asynchronous (ASGI) applications with Django
  • Set up a production environment for your projects
  • Easily create complex web applications to solve real use cases

Who this book is for

This book is for readers with basic Python knowledge and programmers transitioning from other web frameworks who wish to learn Django by doing. If you already use Django or have in the past, and want to learn best practices and integrate other technologies to scale your applications, then this book is for you too. This book will help you master the most relevant areas of the framework by building practical projects from scratch. Some previous knowledge of HTML and JavaScript is assumed.

Publisher resources

Download Example Code

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. Building a Blog Application
    1. Installing Python
    2. Creating a Python virtual environment
    3. Installing Django
      1. Installing Django with pip
      2. New features in Django 4
    4. Django overview
    5. Main framework components
    6. The Django architecture
    7. Creating your first project
      1. Applying initial database migrations
      2. Running the development server
      3. Project settings
      4. Projects and applications
      5. Creating an application
    8. Creating the blog data models
      1. Creating the Post model
      2. Adding datetime fields
      3. Defining a default sort order
      4. Adding a database index
      5. Activating the application
      6. Adding a status field
      7. Adding a many-to-one relationship
      8. Creating and applying migrations
    9. Creating an administration site for models
      1. Creating a superuser
      2. The Django administration site
      3. Adding models to the administration site
      4. Customizing how models are displayed
    10. Working with QuerySets and managers
      1. Creating objects
      2. Updating objects
      3. Retrieving objects
        1. Using the filter() method
        2. Using exclude()
        3. Using order_by()
      4. Deleting objects
      5. When QuerySets are evaluated
      6. Creating model managers
    11. Building list and detail views
      1. Creating list and detail views
      2. Using the get_object_or_404 shortcut
      3. Adding URL patterns for your views
    12. Creating templates for your views
      1. Creating a base template
      2. Creating the post list template
      3. Accessing our application
      4. Creating the post detail template
    13. The request/response cycle
    14. Additional resources
    15. Summary
    16. Join us on Discord.
  3. Enhancing Your Blog with Advanced Features
    1. Using canonical URLs for models
    2. Creating SEO-friendly URLs for posts
    3. Modifying the URL patterns
    4. Modifying the views
    5. Modifying the canonical URL for posts
    6. Adding pagination
      1. Adding pagination to the post list view
      2. Creating a pagination template
      3. Handling pagination errors
    7. Building class-based views
      1. Why use class-based views
      2. Using a class-based view to list posts
    8. Recommending posts by email
      1. Creating forms with Django
      2. Handling forms in views
      3. Sending emails with Django
      4. Sending emails in views
      5. Rendering forms in templates
    9. Creating a comment system
      1. Creating a model for comments
      2. Adding comments to the administration site
      3. Creating forms from models
      4. Handling ModelForms in views
      5. Creating templates for the comment form
      6. Adding comments to the post detail view
      7. Adding comments to the post detail template
    10. Additional resources
    11. Summary
  4. Extending Your Blog Application
    1. Adding the tagging functionality
    2. Retrieving posts by similarity
    3. Creating custom template tags and filters
      1. Implementing custom template tags
      2. Creating a simple template tag
      3. Creating an inclusion template tag
      4. Creating a template tag that returns a QuerySet
      5. Implementing custom template filters
      6. Creating a template filter to support Markdown syntax
    4. Adding a sitemap to the site
    5. Creating feeds for blog posts
    6. Adding full-text search to the blog
      1. Installing PostgreSQL
      2. Creating a PostgreSQL database
      3. Dumping the existing data
      4. Switching the database in the project
      5. Loading the data into the new database
      6. Simple search lookups
      7. Searching against multiple fields
      8. Building a search view
      9. Stemming and ranking results
      10. Stemming and removing stop words in different languages
      11. Weighting queries
      12. Searching with trigram similarity
    7. Additional resources
    8. Summary
  5. Building a Social Website
    1. Creating a social website project
      1. Starting the social website project
    2. Using the Django authentication framework
      1. Creating a login view
      2. Using Django authentication views
      3. Login and logout views
      4. Change password views
      5. Reset password views
    3. User registration and user profiles
      1. User registration
      2. Extending the user model
      3. Installing Pillow and serving media files
      4. Creating migrations for the profile model
        1. Using a custom user model
      5. Using the messages framework
    4. Building a custom authentication backend
      1. Preventing users from using an existing email
    5. Additional resources
    6. Summary
    7. Join us on Discord.
  6. Implementing Social Authentication
    1. Adding social authentication to your site
      1. Running the development server through HTTPS
      2. Authentication using Facebook
      3. Authentication using Twitter
      4. Authentication using Google
      5. Creating a profile for users that register with social authentication
    2. Additional resources
    3. Summary
  7. Sharing Content on Your Website
    1. Creating an image bookmarking website
      1. Building the image model
      2. Creating many-to-many relationships
      3. Registering the image model in the administration site
    2. Posting content from other websites
      1. Cleaning form fields
      2. Installing the Requests library
      3. Overriding the save() method of a ModelForm
      4. Building a bookmarklet with JavaScript
    3. Creating a detail view for images
    4. Creating image thumbnails using easy-thumbnails
    5. Adding asynchronous actions with JavaScript
      1. Loading JavaScript on the DOM
      2. Cross-site request forgery for HTTP requests in JavaScript
      3. Performing HTTP requests with JavaScript
    6. Adding infinite scroll pagination to the image list
    7. Additional resources
    8. Summary
  8. Tracking User Actions
    1. Building a follow system
      1. Creating many-to-many relationships with an intermediary model
      2. Creating list and detail views for user profiles
      3. Adding user follow/unfollow actions with JavaScript
    2. Building a generic activity stream application
      1. Using the contenttypes framework
      2. Adding generic relations to your models
      3. Avoiding duplicate actions in the activity stream
      4. Adding user actions to the activity stream
      5. Displaying the activity stream
      6. Optimizing QuerySets that involve related objects
        1. Using select_related()
        2. Using prefetch_related()
      7. Creating templates for actions
    3. Using signals for denormalizing counts
      1. Working with signals
      2. Application configuration classes
    4. Using Django Debug Toolbar
      1. Installing Django Debug Toolbar
      2. Django Debug Toolbar panels
      3. Django Debug Toolbar commands
    5. Counting image views with Redis
      1. Installing Docker
      2. Installing Redis
      3. Using Redis with Python
      4. Storing image views in Redis
      5. Storing a ranking in Redis
      6. Next steps with Redis
    6. Additional resources
    7. Summary
  9. Building an Online Shop
    1. Creating an online shop project
      1. Creating product catalog models
      2. Registering catalog models on the administration site
      3. Building catalog views
      4. Creating catalog templates
    2. Building a shopping cart
      1. Using Django sessions
      2. Session settings
      3. Session expiration
      4. Storing shopping carts in sessions
      5. Creating shopping cart views
        1. Adding items to the cart
        2. Building a template to display the cart
        3. Adding products to the cart
        4. Updating product quantities in the cart
      6. Creating a context processor for the current cart
        1. Context processors
        2. Setting the cart into the request context
    3. Registering customer orders
      1. Creating order models
      2. Including order models in the administration site
      3. Creating customer orders
    4. Asynchronous tasks
      1. Working with asynchronous tasks
      2. Workers, message queues, and message brokers
        1. Using Django with Celery and RabbitMQ
        2. Monitoring Celery with Flower
    5. Additional resources
    6. Summary
    7. Join us on Discord.
  10. Managing Payments and Orders
    1. Integrating a payment gateway
      1. Creating a Stripe account
      2. Installing the Stripe Python library
      3. Adding Stripe to your project
      4. Building the payment process
        1. Integrating Stripe Checkout
      5. Testing the checkout process
        1. Using test credit cards
        2. Checking the payment information in the Stripe dashboard
      6. Using webhooks to receive payment notifications
        1. Creating a webhook endpoint
        2. Testing webhook notifications
      7. Referencing Stripe payments in orders
      8. Going live
    2. Exporting orders to CSV files
      1. Adding custom actions to the administration site
    3. Extending the administration site with custom views
    4. Generating PDF invoices dynamically
      1. Installing WeasyPrint
      2. Creating a PDF template
      3. Rendering PDF files
      4. Sending PDF files by email
    5. Additional resources
    6. Summary
  11. Extending Your Shop
    1. Creating a coupon system
      1. Building the coupon model
      2. Applying a coupon to the shopping cart
      3. Applying coupons to orders
      4. Creating coupons for Stripe Checkout
      5. Adding coupons to orders on the administration site and to PDF invoices
    2. Building a recommendation engine
      1. Recommending products based on previous purchases
    3. Additional resources
    4. Summary
  12. Adding Internationalization to Your Shop
    1. Internationalization with Django
      1. Internationalization and localization settings
      2. Internationalization management commands
      3. Installing the gettext toolkit
      4. How to add translations to a Django project
      5. How Django determines the current language
    2. Preparing your project for internationalization
    3. Translating Python code
      1. Standard translations
      2. Lazy translations
      3. Translations including variables
      4. Plural forms in translations
      5. Translating your own code
    4. Translating templates
      1. The {% trans %} template tag
      2. The {% blocktrans %} template tag
      3. Translating the shop templates
    5. Using the Rosetta translation interface
    6. Fuzzy translations
    7. URL patterns for internationalization
      1. Adding a language prefix to URL patterns
      2. Translating URL patterns
    8. Allowing users to switch language
    9. Translating models with django-parler
      1. Installing django-parler
      2. Translating model fields
      3. Integrating translations into the administration site
      4. Creating migrations for model translations
      5. Using translations with the ORM
      6. Adapting views for translations
    10. Format localization
    11. Using django-localflavor to validate form fields
    12. Additional resources
    13. Summary
  13. Building an E-Learning Platform
    1. Setting up the e-learning project
    2. Serving media files
    3. Building the course models
      1. Registering the models in the administration site
      2. Using fixtures to provide initial data for models
    4. Creating models for polymorphic content
      1. Using model inheritance
        1. Abstract models
        2. Multi-table model inheritance
        3. Proxy models
      2. Creating the Content models
      3. Creating custom model fields
      4. Adding ordering to module and content objects
    5. Adding authentication views
      1. Adding an authentication system
      2. Creating the authentication templates
    6. Additional resources
    7. Summary
    8. Join us on Discord.
  14. Creating a Content Management System
    1. Creating a CMS
      1. Creating class-based views
      2. Using mixins for class-based views
      3. Working with groups and permissions
        1. Restricting access to class-based views
    2. Managing course modules and their contents
      1. Using formsets for course modules
      2. Adding content to course modules
      3. Managing modules and their contents
      4. Reordering modules and their contents
        1. Using mixins from django-braces
    3. Additional resources
    4. Summary
  15. Rendering and Caching Content
    1. Displaying courses
    2. Adding student registration
      1. Creating a student registration view
      2. Enrolling on courses
    3. Accessing the course contents
      1. Rendering different types of content
    4. Using the cache framework
      1. Available cache backends
      2. Installing Memcached
      3. Installing the Memcached Docker image
      4. Installing the Memcached Python binding
      5. Django cache settings
      6. Adding Memcached to your project
      7. Cache levels
      8. Using the low-level cache API
      9. Checking cache requests with Django Debug Toolbar
        1. Caching based on dynamic data
      10. Caching template fragments
      11. Caching views
        1. Using the per-site cache
      12. Using the Redis cache backend
      13. Monitoring Redis with Django Redisboard
    5. Additional resources
    6. Summary
  16. Building an API
    1. Building a RESTful API
      1. Installing Django REST framework
      2. Defining serializers
      3. Understanding parsers and renderers
      4. Building list and detail views
      5. Consuming the API
      6. Creating nested serializers
      7. Building custom API views
      8. Handling authentication
      9. Adding permissions to views
      10. Creating ViewSets and routers
      11. Adding additional actions to ViewSets
      12. Creating custom permissions
      13. Serializing course contents
      14. Consuming the RESTful API
    2. Additional resources
    3. Summary
  17. Building a Chat Server
    1. Creating a chat application
      1. Implementing the chat room view
    2. Real-time Django with Channels
      1. Asynchronous applications using ASGI
      2. The request/response cycle using Channels
    3. Installing Channels
    4. Writing a consumer
    5. Routing
    6. Implementing the WebSocket client
    7. Enabling a channel layer
      1. Channels and groups
      2. Setting up a channel layer with Redis
      3. Updating the consumer to broadcast messages
      4. Adding context to the messages
    8. Modifying the consumer to be fully asynchronous
    9. Integrating the chat application with existing views
    10. Additional resources
    11. Summary
  18. Going Live
    1. Creating a production environment
      1. Managing settings for multiple environments
        1. Local environment settings
        2. Running the local environment
        3. Production environment settings
    2. Using Docker Compose
      1. Installing Docker Compose
      2. Creating a Dockerfile
      3. Adding the Python requirements
      4. Creating a Docker Compose file
      5. Configuring the PostgreSQL service
      6. Applying database migrations and creating a superuser
      7. Configuring the Redis service
    3. Serving Django through WSGI and NGINX
      1. Using uWSGI
      2. Configuring uWSGI
      3. Using NGINX
      4. Configuring NGINX
      5. Using a hostname
      6. Serving static and media assets
        1. Collecting static files
        2. Serving static files with NGINX
    4. Securing your site with SSL/TLS
      1. Checking your project for production
      2. Configuring your Django project for SSL/TLS
      3. Creating an SSL/TLS certificate
      4. Configuring NGINX to use SSL/TLS
      5. Redirecting HTTP traffic over to HTTPS
    5. Using Daphne for Django Channels
      1. Using secure connections for WebSockets
      2. Including Daphne in the NGINX configuration
    6. Creating a custom middleware
      1. Creating a subdomain middleware
        1. Serving multiple subdomains with NGINX
    7. Implementing custom management commands
    8. Additional resources
    9. Summary
  19. Other Books You May Enjoy
  20. Index

Product information

  • Title: Django 4 By Example - Fourth Edition
  • Author(s): Antonio Melé
  • Release date: August 2022
  • Publisher(s): Packt Publishing
  • ISBN: 9781801813051