Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-04-02

AuthorMalhar Lathkar

Django has evolved into a powerful full-stack framework ideal for developing data-driven web applications, continuously expanding with new tools for asynchronous solutions, APIs, and real-time applications. This book explores modern Django development best practices, including Django Channels for WebSockets, Django REST Framework (DRF) for REST APIs, Graphene and Strawberry for GraphQL APIs, and integrating a front-end built with React The content is structured into two main parts, covering both fundamental and advanced concepts in a practical and digestible manner. The first part introduces Django's core concepts, starting with an overview of web development and Python’s asyncio module for asynchronous processing. It then walks you through Django installation, project setup, and the admin interface. The Model-View-Template (MVT) architecture is explained in depth, with chapters on models, views, and templates, illustrating real-world examples. Additionally, it covers database interactions, introducing SQLAlchemy ORM and MongoDB integration to extend Django’s capabilities beyond its default ORM. The second part delves into advanced Django features and the broader ecosystem. Topics include authentication, security, messaging, and reusable apps such as the Django toolbar. REST API development with Django REST Framework is explored, followed by an introduction to building GraphQL APIs using Graphene and Strawberry. A dedicated chapter covers Django Channels and the WebSocket protocol for real-time applications. Modern Django Web Development concludes with integrating React to develop front-end clients for Django-based REST, GraphQL, and WebSocket APIs, enabling a full-stack development experience. Who is it for: Software developers, web developers and engineers who are interested in adding Django to their development skillset. Python Developers can also leverage the power of modern Django with the help of this practical guide.

Tags
No tags
ISBN: 8868814714
Publisher: Apress
Publish Year: 2025
Language: 英文
Pages: 441
File Format: PDF
File Size: 15.1 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Modern Django Web Development With Channels, DRF, GraphQL, and React — Malhar Lathkar
Modern Django Web Development With Channels, DRF, GraphQL, and React Malhar Lathkar
Modern Django Web Development: With Channels, DRF, GraphQL, and React ISBN-13 (pbk): 979-8-8688-1471-6 ISBN-13 (electronic): 979-8-8688-1472-3 https://doi.org/10.1007/979-8-8688-1472-3 Copyright © 2025 by Malhar Lathkar This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: James Robinson-Prior, Divya Modi Development Editor: James Markham Coordinating Editor: Jacob Shmulewitz Cover designed by eStudioCalamar Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@ springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub (https://github.com/Apress). For more detailed information, please visit https://www.apress.com/gp/services/source-code. If disposing of this product, please recycle the paper Malhar Lathkar Nanded, Maharashtra, India
It's been a great privilege to have learned from many exceptional teachers, who taught from the heart and not just the book. I dedicate this work to all of them.
v Table of Contents About the Author �������������������������������������������������������������������������������xiii About the Technical Reviewer ������������������������������������������������������������xv Acknowledgments ����������������������������������������������������������������������������xvii Introduction ���������������������������������������������������������������������������������������xix Chapter 1: Django Basics ���������������������������������������������������������������������1 Introduction �����������������������������������������������������������������������������������������������������������1 Fundamentals of HTTP ������������������������������������������������������������������������������������������2 HTTP Methods �������������������������������������������������������������������������������������������������������4 POST Method ���������������������������������������������������������������������������������������������������4 GET Method �����������������������������������������������������������������������������������������������������4 PUT Method �����������������������������������������������������������������������������������������������������5 DELETE Method �����������������������������������������������������������������������������������������������5 CGI �������������������������������������������������������������������������������������������������������������������������6 WSGI����������������������������������������������������������������������������������������������������������������������7 wsgiref Package ���������������������������������������������������������������������������������������������������8 What Is a Web Framework? ��������������������������������������������������������������������������������11 MVC vs� MVT �������������������������������������������������������������������������������������������������������14 Asynchronous Processing �����������������������������������������������������������������������������������16 asyncio Module ���������������������������������������������������������������������������������������������16 ASGI ��������������������������������������������������������������������������������������������������������������������19
vi Overview of Django ���������������������������������������������������������������������������������������������21 Batteries Included �����������������������������������������������������������������������������������������21 Utility Apps �����������������������������������������������������������������������������������������������������21 Scalability ������������������������������������������������������������������������������������������������������22 Documentation and Support ��������������������������������������������������������������������������22 Summary�������������������������������������������������������������������������������������������������������������22 Chapter 2: Django: First Steps ������������������������������������������������������������23 Install Django ������������������������������������������������������������������������������������������������������24 Installation on Ubuntu������������������������������������������������������������������������������������24 Installation on Windows���������������������������������������������������������������������������������28 Set Up the Django Project �����������������������������������������������������������������������������������29 Django App ����������������������������������������������������������������������������������������������������������33 Add an App ����������������������������������������������������������������������������������������������������35 Define Views ��������������������������������������������������������������������������������������������������35 Define urlpatterns ������������������������������������������������������������������������������������������36 Update URLCONF �������������������������������������������������������������������������������������������37 Path Parameters ��������������������������������������������������������������������������������������������38 Serving Web Pages ����������������������������������������������������������������������������������������40 Admin Site �����������������������������������������������������������������������������������������������������������43 Summary�������������������������������������������������������������������������������������������������������������49 Chapter 3: Django ORM �����������������������������������������������������������������������51 DB-API �����������������������������������������������������������������������������������������������������������������52 What Is ORM? ������������������������������������������������������������������������������������������������������57 Define a Model ����������������������������������������������������������������������������������������������������60 Database Configuration ���������������������������������������������������������������������������������������61 Run Migrations ����������������������������������������������������������������������������������������������������62 Register Model with Admin Site ��������������������������������������������������������������������������64 Table of ConTenTs
vii Django Admin Shell ���������������������������������������������������������������������������������������������65 Add Objects ���������������������������������������������������������������������������������������������������66 Retrieval ��������������������������������������������������������������������������������������������������������67 Search �����������������������������������������������������������������������������������������������������������69 Updating the Objects �������������������������������������������������������������������������������������70 Model Field Types �����������������������������������������������������������������������������������������������72 CharField �������������������������������������������������������������������������������������������������������73 IntegerField ���������������������������������������������������������������������������������������������������73 FloatField �������������������������������������������������������������������������������������������������������74 BooleanField ��������������������������������������������������������������������������������������������������74 DateField �������������������������������������������������������������������������������������������������������74 Types of Relationships ����������������������������������������������������������������������������������������75 One-to-One Relationship �������������������������������������������������������������������������������77 One-to-Many Relationship �����������������������������������������������������������������������������79 Many-to-Many Relationship ��������������������������������������������������������������������������80 Summary�������������������������������������������������������������������������������������������������������������82 Chapter 4: Django Templates ��������������������������������������������������������������85 Template Object ��������������������������������������������������������������������������������������������������86 render( ) Function ������������������������������������������������������������������������������������������������90 Template Context ������������������������������������������������������������������������������������������������90 Template Tags �����������������������������������������������������������������������������������������������������92 {% if %} Tag ���������������������������������������������������������������������������������������������������93 {% for %} Tag �������������������������������������������������������������������������������������������������96 Form Templates ������������������������������������������������������������������������������������������������100 HTML Form ��������������������������������������������������������������������������������������������������100 Form Class ���������������������������������������������������������������������������������������������������103 ModelForm ��������������������������������������������������������������������������������������������������108 Table of ConTenTs
viii Class-Based View ���������������������������������������������������������������������������������������������111 Generic Views ���������������������������������������������������������������������������������������������������114 TemplateView ����������������������������������������������������������������������������������������������114 CreateView ��������������������������������������������������������������������������������������������������116 UpdateView �������������������������������������������������������������������������������������������������118 DeleteView ���������������������������������������������������������������������������������������������������119 DetailView ����������������������������������������������������������������������������������������������������121 ListView �������������������������������������������������������������������������������������������������������122 Static Files ��������������������������������������������������������������������������������������������������������125 Image As Static Asset ����������������������������������������������������������������������������������129 CSS and JavaScript �������������������������������������������������������������������������������������131 Template Inheritance ����������������������������������������������������������������������������������������134 {% include %} Tag ����������������������������������������������������������������������������������������135 {% block %} Tag �������������������������������������������������������������������������������������������139 {% extends %} Tag ���������������������������������������������������������������������������������������140 Summary�����������������������������������������������������������������������������������������������������������143 Chapter 5: Django: Using Databases�������������������������������������������������145 SQLAlchemy ORM ���������������������������������������������������������������������������������������������146 Engine ����������������������������������������������������������������������������������������������������������148 Table in SQLAlchemy Core ���������������������������������������������������������������������������149 Model �����������������������������������������������������������������������������������������������������������151 Session ��������������������������������������������������������������������������������������������������������153 Alembic �������������������������������������������������������������������������������������������������������������156 Advent of NOSQL Databases �����������������������������������������������������������������������������161 MongoDB�����������������������������������������������������������������������������������������������������������162 Table of ConTenTs
ix Installation ��������������������������������������������������������������������������������������������������������162 Local Deployment ����������������������������������������������������������������������������������������162 Atlas ������������������������������������������������������������������������������������������������������������163 MongoDB Shell ��������������������������������������������������������������������������������������������164 Compass ������������������������������������������������������������������������������������������������������166 PyMongo �����������������������������������������������������������������������������������������������������������171 Insert Document ������������������������������������������������������������������������������������������172 Retrieval ������������������������������������������������������������������������������������������������������173 MongoEngine ����������������������������������������������������������������������������������������������������176 Document Class �������������������������������������������������������������������������������������������177 Connection ���������������������������������������������������������������������������������������������������178 DynamicDocument ��������������������������������������������������������������������������������������181 Djongo ���������������������������������������������������������������������������������������������������������������183 Summary�����������������������������������������������������������������������������������������������������������186 Chapter 6: Advanced Django ������������������������������������������������������������187 Messages Framework ���������������������������������������������������������������������������������������187 Cookies ��������������������������������������������������������������������������������������������������������188 Sessions ������������������������������������������������������������������������������������������������������189 Activating Messaging ����������������������������������������������������������������������������������190 Storage Backends ���������������������������������������������������������������������������������������192 Adding Messages ����������������������������������������������������������������������������������������193 Fetching Messages ��������������������������������������������������������������������������������������194 Authentication ���������������������������������������������������������������������������������������������������197 Login and Logout �����������������������������������������������������������������������������������������198 New User �����������������������������������������������������������������������������������������������������202 @login_required( ) ���������������������������������������������������������������������������������������204 Table of ConTenTs
x Security Features ����������������������������������������������������������������������������������������������207 CSRF ������������������������������������������������������������������������������������������������������������207 XSS ��������������������������������������������������������������������������������������������������������������209 SQL Injection �����������������������������������������������������������������������������������������������211 async Views ������������������������������������������������������������������������������������������������������213 Adapter Functions ���������������������������������������������������������������������������������������217 async Querysets ������������������������������������������������������������������������������������������218 Reusable Apps ��������������������������������������������������������������������������������������������������218 Django Debug Toolbar ���������������������������������������������������������������������������������������223 Summary�����������������������������������������������������������������������������������������������������������228 Chapter 7: REST API with Django������������������������������������������������������229 What Is API? ������������������������������������������������������������������������������������������������������230 REST Architecture ���������������������������������������������������������������������������������������������233 Uniform Interface �����������������������������������������������������������������������������������������233 Statelessness ����������������������������������������������������������������������������������������������234 Client-Server �����������������������������������������������������������������������������������������������234 Cacheability �������������������������������������������������������������������������������������������������234 Layered System �������������������������������������������������������������������������������������������235 Code on Demand �����������������������������������������������������������������������������������������235 Serialization ������������������������������������������������������������������������������������������������������235 Django REST Framework ����������������������������������������������������������������������������������238 DRF – Get Started ����������������������������������������������������������������������������������������238 Serializer Class ��������������������������������������������������������������������������������������������244 ModelSerializer ��������������������������������������������������������������������������������������������249 DRF – Class-Based Views ����������������������������������������������������������������������������264 DRF – Generic Views �����������������������������������������������������������������������������������267 ViewSets ������������������������������������������������������������������������������������������������������271 Table of ConTenTs
xi Routers ��������������������������������������������������������������������������������������������������������273 DRF – Authentication �����������������������������������������������������������������������������������276 Alternatives to DRF �������������������������������������������������������������������������������������������288 Django Ninja ������������������������������������������������������������������������������������������������������289 Summary�����������������������������������������������������������������������������������������������������������298 Chapter 8: GraphQL with Django �������������������������������������������������������299 GraphQL vs� REST ���������������������������������������������������������������������������������������������300 GraphQL Architecture ����������������������������������������������������������������������������������������301 Schema Definition Language ����������������������������������������������������������������������������302 Types �����������������������������������������������������������������������������������������������������������302 Queries ��������������������������������������������������������������������������������������������������������304 Mutations �����������������������������������������������������������������������������������������������������305 Subscriptions �����������������������������������������������������������������������������������������������306 Schema��������������������������������������������������������������������������������������������������������307 GraphQL and Python �����������������������������������������������������������������������������������������308 Strawberry ��������������������������������������������������������������������������������������������������������309 Strawberry-Django ��������������������������������������������������������������������������������������������316 Graphene �����������������������������������������������������������������������������������������������������������322 Graphene-Django ����������������������������������������������������������������������������������������������330 Summary�����������������������������������������������������������������������������������������������������������334 Chapter 9: WebSockets with Django �������������������������������������������������335 WebSocket Protocol ������������������������������������������������������������������������������������������336 WebSocket and Python �������������������������������������������������������������������������������������338 Django Channels �����������������������������������������������������������������������������������������������344 Consumers ��������������������������������������������������������������������������������������������������������348 Routing ��������������������������������������������������������������������������������������������������������������349 Table of ConTenTs
xii Channel Layers �������������������������������������������������������������������������������������������������354 Single Channel���������������������������������������������������������������������������������������������356 Groups ���������������������������������������������������������������������������������������������������������356 WebSocket Client Template �������������������������������������������������������������������������������358 Login/Logout �����������������������������������������������������������������������������������������������������360 Summary�����������������������������������������������������������������������������������������������������������362 Chapter 10: ReactJS with Django �����������������������������������������������������363 ReactJS �������������������������������������������������������������������������������������������������������������364 React App ����������������������������������������������������������������������������������������������������������366 React Developer Tools ���������������������������������������������������������������������������������������370 What Is Promise? ����������������������������������������������������������������������������������������������370 useState Hook ���������������������������������������������������������������������������������������������������372 useEffect Hook ��������������������������������������������������������������������������������������������������373 Axios �����������������������������������������������������������������������������������������������������������������374 DRF Backend �����������������������������������������������������������������������������������������������381 Axios Frontend ���������������������������������������������������������������������������������������������385 Apollo ����������������������������������������������������������������������������������������������������������������394 Graphene-Django Backend ��������������������������������������������������������������������������398 Apollo Frontend �������������������������������������������������������������������������������������������400 BookList Component������������������������������������������������������������������������������������401 React for WebSocket �����������������������������������������������������������������������������������������404 Summary�����������������������������������������������������������������������������������������������������������410 Index �������������������������������������������������������������������������������������������������411 Table of ConTenTs
xiii About the Author Malhar Lathkar brings over 35 years of experience as an independent software developer, entrepreneur, author, trainer, and mentor. Though formally trained in electronics at the postgraduate level, he has successfully transitioned into the profession of software training and development as a self- taught expert. A passionate educator at heart, Malhar has positively impacted the careers of countless students and professionals worldwide, particularly in the technologies related to Python and Java. He actively collaborates with various EdTech companies as a subject matter expert, contributing to the design of high-quality training programs. He is a recognized author with works featured by prominent publishing houses, including his 2023 FastAPI book with Apress. Malhar also provides corporate training. He is frequently invited to conduct workshops and deliver technical talks to students in various institutions. Beyond his professional pursuits, Malhar enjoys Indian classical music and is an avid sports enthusiast.
xv About the Technical Reviewer Rajiv Tulsyan is an accomplished Solutions Architect with a distinguished career spanning over two decades, marked by a proven track record in architecting distributed systems and driving enterprise-level technology road maps on a global scale. His expertise encompasses a spectrum of skills, from designing and building accelerators to a deep understanding of SOA, event-driven, and Microservices event-based architectures. Rajiv’s mastery extends to cloud technologies, including Hybrid Cloud Architecture and managed services, coupled with proficiency in Java, Kubernetes, Docker, and API gateway technologies. As a Solutions Architect, he is currently steering the design of architecture strategies for large-scale application deployments, showcasing his commitment to scalable, resilient, and innovative solutions. Rajiv’s career journey reflects not only technical acumen but also leadership and a passion for developing technical talent, positioning him as a luminary in the ever-evolving landscape of technology. With an academic background featuring an MS in Consulting Management from BITS Pilani, India, and an MCA in Computer Application from MDU Rohtak, Rajiv Tulsyan has seamlessly blended theoretical knowledge with practical application throughout his career. From leading a medium-sized Integration Architecture practice at Software AG to heading the B2B Practice and Knowledge Management Practice, Rajiv’s management experience is as robust as his technical expertise. His commitment to excellence is underscored by certifications
xvi such as WebMethods 9.0 Certified ESB Developer, WebMethods Certified BPM Developer, and TOGAF 9.2: Enterprise Architecture, positioning him as a thought leader in the field. Rajiv Tulsyan’s career stands as a testament to his dedication to pushing the boundaries of technology and fostering an atmosphere of technical excellence.    abouT The TeChniCal RevieweR
xvii Acknowledgments My previous work High-Performance Web Apps with FastAPI, published by Apress (Springer Nature) in 2023, has been well received. I am deeply grateful to them for their continued support. It is a privilege to partner with a distinguished brand like Apress. I thank the editorial team for entrusting me with another opportunity to share my knowledge through this book. This book would not have been possible without the invaluable contributions of many individuals. First and foremost, I extend my heartfelt gratitude to James Robinson-Prior and Divya Modi – both highly skilled editors – for their support, guidance, and feedback during the various stages of the process of finalizing the draft of this book. I would also like to express my sincere appreciation to Rajiv Tulsyan (the technical reviewer) for his expert insights and invaluable suggestions to make the content as authentic as possible. Murlimohan Kanagala has been a close friend for almost three decades. Frequent constructive interactions with him have always been immensely helpful in my journey as a developer, author, and educator. I take this opportunity to acknowledge his support. Treading an offbeat career path is never easy, unless you have a strong support system of friends and family. I can't resist thanking my wife, Jayashree, for being with me through the good and bad times. Finally, sincere thanks from the bottom of my heart to my students, colleagues, and collaborators.
xix Introduction Django is by far the most preferred Python framework for developing data-driven web applications. Over the period, it has evolved to become a powerful full-stack framework, growing and expanding its capabilities for building asynchronous solutions, APIs, and real-time applications. This book aims to equip the reader with the core concepts of Django and to highlight new facets and best practices of web application development with Modern Django. It emphasizes features such as Channels for the implementation of the WebSocket protocol, DRF for building REST APIs, using Graphene and Strawberry for GraphQL APIs, and developing a frontend app with React JS. How This Book Is Arranged This book comprises ten chapters. They are organized into two distinct parts. The first part deals with the basics of Django development, describing the MVT architecture of Django with a lot of practical, real-world examples. Chapter 1 (Django Basics) sets the ball rolling by explaining the concepts of web development. It introduces Python's asyncio module for asynchronous processing and gives an overview of the Django framework. Chapter 2 (Django: First Steps) guides you through the installation of Django and creating your first Django application. It also gives a detailed explanation of Django's Admin interface.
xx Chapter 3 (Django ORM) deals with an important aspect of Django's MVT architecture – models. You will learn how to use Django Shell, model fields, and their types and the relationships. Chapter 4 (Django Templates) covers the View component of Django's architecture. You will learn about various template tags, different types of views, and the static assets. Chapter 5 (Django: Using Databases) is aimed at enabling you to work with a wider range of databases. You will use SQLAlchemy ORM and different libraries that let you use MongoDB as a backend to your Django application. In the second part, more advanced features of Django and various apps in the Django ecosystem are discussed. Chapter 6 (Advanced Django) will cover features such as messaging, authentication, and security. It also discusses how to build and include reusable apps such as the Django Debug Toolbar. Chapter 7 (REST API with Django) helps you to explore the powerful features of Django REST Framework to build robust REST APIs with Django. Chapter 8 (GraphQL with Django) explains the basics of GraphQL protocol and discusses how to use Graphene and Strawberry packages for building GraphQL API with Django. Chapter 9 (WebSockets with Django) takes a detailed look at the WebSocket protocol and its implementation in Django with the Django Channels app. Chapter 10 (ReactJS with Django) teaches you to use ReactJS to build frontend clients for your Django-based REST, GraphQL, and WebSocket APIs. Thus, this book, Modern Django Web Development, will be a comprehensive guide that covers all the aspects required for creating successful and easy-to-use Django web applications. inTRoduCTion
1© Malhar Lathkar 2025 M. Lathkar, Modern Django Web Development, https://doi.org/10.1007/979-8-8688-1472-3_1 CHAPTER 1 Django Basics Introduction Even after more than a decade and a half since the release of its earliest version, Django is still the most popular web framework of Python developers. The enduring relevance of Django can be attributed to its continuing evolution by incorporating modern trends in the web development technology. The latest version of Django (Django 5.0), released in December 2023, also includes a number of new features that enhance Django’s versatility, scalability, and maturity and provide a cleaner architecture. Before embarking upon our journey to learn to develop Modern Django-based web applications, let us refresh some of the fundamental concepts of web development. This chapter covers the following topics: • Fundamentals of HTTP • HTTP methods • CGI • WSGI • wsgiref package
2 • What is a web framework? • MVC vs. MVT • Asynchronous processing • ASGI • Overview of Django Fundamentals of HTTP Let us start with HTTP (Hypertext Transfer Protocol), since it is the backbone of any data exchange over the World Wide Web. It is an application layer protocol built on top of a TCP connection. The HTTP follows a client-server communication model, wherein an HTTP client (generally a web browser) opens a connection with the server and initiates a request for a certain resource to be served to it. The web application hosted on the HTTP server accepts the request, processes it, and sends back an appropriate response. The web application interacts with a database and may use certain static resources such as images and documents to formulate the response. On receiving the server’s response, it is rendered by the client, and the connection it has opened is either used for further requests or it is closed. Thus, the request-response cycle, as depicted in Figure 1-1, drives the HTTP communication. ChapTeR 1 django basiCs