Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Django 5 By Example

You're reading from   Django 5 By Example Build powerful and reliable Python web applications from scratch

Arrow left icon
Product type Paperback
Published in Apr 2024
Last Updated in Oct 2025
Publisher Packt
ISBN-13 9781805125457
Length 826 pages
Edition 5th Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Antonio Melé Antonio Melé
Author Profile Icon Antonio Melé
Antonio Melé
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Building a Blog Application FREE CHAPTER 2. Enhancing Your Blog and Adding Social Features 3. Extending Your Blog Application 4. Building a Social Website 5. Implementing Social Authentication 6. Sharing Content on Your Website 7. Tracking User Actions 8. Building an Online Shop 9. Managing Payments and Orders 10. Extending Your Shop 11. Adding Internationalization to Your Shop 12. Building an E-Learning Platform 13. Creating a Content Management System 14. Rendering and Caching Content 15. Building an API 16. Building a Chat Server 17. Going Live 18. Other Books You May Enjoy
19. Index

Django overview

Django is a framework consisting of a set of components that solve common web development problems. Django components are loosely coupled, which means they can be managed independently. This helps separate the responsibilities of the different layers of the framework; the database layer knows nothing about how the data is displayed, the template system knows nothing about web requests, and so on.

Django offers maximum code reusability by following the DRY (don’t repeat yourself) principle. Django also fosters rapid development and allows you to use less code by taking advantage of Python’s dynamic capabilities, such as introspection.

You can read more about Django’s design philosophies at https://docs.djangoproject.com/en/5.2/misc/design-philosophies/.

Main framework components

Django follows the MTV (Model-Template-View) pattern. It is a slightly similar pattern to the well-known MVC (Model-View-Controller) pattern, where the template acts as the view and the framework itself acts as the controller.

The responsibilities in the Django MTV pattern are divided as follows:

  • Model: This defines the logical data structure and is the data handler between the database and the view.
  • Template: This is the presentation layer. Django uses a plain-text template system that keeps everything that the browser renders.
  • View: This communicates with the database via the model and transfers the data to the template for viewing.

The framework itself acts as the controller. It sends a request to the appropriate view, according to the Django URL configuration.

When developing any Django project, you will always work with models, views, templates, and URLs. In this chapter, you will learn how they fit together.

The Django architecture

Figure 1.4 shows how Django processes requests and how the request/response cycle is managed with the different main Django components – URLs, views, models, and templates:

Diagram

Description automatically generated

Figure 1.4: The Django architecture

A magnifying glass on a black background

AI-generated content may be incorrect.Quick tip: Need to see a high-resolution version of this image? Open this book in the next-gen Packt Reader or view it in the PDF/ePub copy.

The next-gen Packt Reader and a free PDF/ePub copy of this book are included with your purchase. Scan the QR code OR visit https://packtpub.com/unlock, then use the search bar to find this book by name. Double-check the edition shown to make sure you get the right one.

This is how Django handles HTTP requests and generates responses:

  1. A web browser requests a page by its URL and the web server passes the HTTP request to Django.
  2. Django runs through its configured URL patterns and stops at the first one that matches the requested URL.
  3. Django executes the view that corresponds to the matched URL pattern.
  4. The view potentially uses data models to retrieve information from the database.
  5. Data models provide data definitions and behaviors. They are used to query the database.
  6. The view renders a template (usually HTML) to display the data and returns it with an HTTP response.

We will get back to the Django request/response cycle at the end of this chapter in the The request/response cycle section.

Django also includes hooks in the request/response process, which are called middleware. Middleware has been intentionally left out of this diagram for the sake of simplicity. You will use middleware in different examples of this book, and you will learn how to create custom middleware in Chapter 17, Going Live.

We have covered the foundational elements of Django and how it processes requests. Let’s explore the new features introduced in Django 5.

New features in Django 5

Django 5 introduced several key features that you will use in the examples of this book. This version also deprecated certain features and eliminated previously deprecated functionalities. Here are some of the new major features introduced:

  • Facet filters in the administration site: Facet filters can be added now to the administration site. When enabled, facet counts are displayed for applied filters in the admin object list. This feature is presented in the Added facet counts to filters section of this chapter.
  • Simplified templates for form field rendering: Form field rendering has been simplified with the capability to define field groups with associated templates. This aims to make the process of rendering related elements of a Django form field, such as labels, widgets, help text, and errors, more streamlined. An example of using field groups can be found in the Creating templates for the comment form section of Chapter 2, Enhancing Your Blog and Adding Social Features.
  • Database-computed default values: Django adds database-computed default values. An example of this feature is presented in the Adding datetime fields section of this chapter.
  • Database-generated model fields: This is a new type of field that enables you to create database-generated columns. An expression is used to automatically set the field value each time the model is changed. The field value is set using the GENERATED ALWAYS SQL syntax.
  • More options for declaring model field choices: Fields that support choices no longer require accessing the .choices attribute to access enumeration types. A mapping or callable instead of an iterable can be used directly to expand enumeration types. Choices with enumeration types in this book have been updated to reflect these changes. An instance of this can be found in the Adding a status field section of this chapter.

Django 5 also came with some improvements in asynchronous support. Asynchronous Server Gateway Interface (ASGI) support was first introduced in Django 3 and improved in Django 4.1 with asynchronous handlers for class-based views and an asynchronous ORM interface. Django 5 adds asynchronous functions to the authentication framework, provides support for asynchronous signal dispatching, and adds asynchronous support to multiple built-in decorators.

Since then, Django 5.1 and 5.2 have been released. Django 5.1 dropped support for Python 3.8 and 3.9, and introduced the following major features:

  • The {% querystring %} template tag: This template tag simplifies the modification of query parameters in URLs, making it easier to generate links that maintain existing query parameters while adding or changing specific ones.
  • Connection pool support for PostgreSQL: Establishing a new connection can take a relatively long time, but keeping connections open can reduce latency.
  • LoginRequiredMiddleware: If installed, the new middleware redirects all unauthenticated requests to a login page. Views can allow unauthenticated requests by using the new login_not_required() decorator.

Meanwhile, Django 5.2 introduced the following new major features:

  • Automatic model imports in the shell: The Django shell now automatically imports the models from your installed applications, which makes running queries much faster by taking away the need for you to import the models you need.
  • Composite Primary Keys: Django is now better aligned with the functionality of SQL, with the ability to define a composite primary key for your models. Instead of the regular auto-incrementing integer values, you define fields in the model whose values become the primary key.
  • Overriding BoundField: It is now easier to override BoundField on forms which makes adding classes for styling much simpler.

For further information on the changes introduced in 5.1 and 5.2, see the Appendix. As a time-based release, there are no drastic changes in Django 5, making it straightforward to upgrade Django 4 applications to the 5.2 release.

You can access the Appendix through the following link: https://packt.link/1g7Af.

If you want to quickly upgrade an existing Django project to the 5.2 release, you can use the django-upgrade tool. This package rewrites the files of your project by applying fixers up to a target version. You can find instructions to use django-upgrade at https://github.com/adamchainz/django-upgrade.

The django-upgrade tool is inspired by the pyupgrade package. You can use pyupgrade to automatically upgrade syntax for newer versions of Python. You can find more information about pyupgrade at https://github.com/asottile/pyupgrade.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Django 5 By Example
You have been reading a chapter from
Django 5 By Example - Fifth Edition
Published in: Apr 2024
Publisher: Packt
ISBN-13: 9781805125457
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Modal Close icon
Modal Close icon