Statistics
4
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-04-02

AuthorSufyan Bin Uzayr

Mastering Django helps the reader master the powerful Django framework for Python for creating dynamic applications and projects. Django is a high-level, open-source Python web framework created to help web developers achieve tight deadlines while also meeting a variety of needs. The primary feature of Django that makes it so popular among developers is that it promotes rapid development while providing a consistent and realistic design. Django is a complete toolkit with a basic code architecture and highly adaptable architecture that promotes rapid development -- it can shape and pace your web app concept and see it through to launch in a matter of hours. Django's simplicity, stability, scalability, and flexibility are unmatched. It is currently a vibrant, collaborative open source project with thousands of users and contributors. Django is a versatile framework capable of developing any website. Robust design, rapid software development, fantastic documentation and tutorials, a vast community with readymade solutions,reasonably easy learning curve, and a high degree of clarity and readability are all hallmarks of this popular web framework. Django has carved out a niche for itself in the industry over the years, and appropriately so. Many popular apps use Django as their secret ingredient. Django has many faetures and can accommodate any modern web application. If you wish to build a successful career in web development, learning Django is a wise choice. With Mastering Django, learning the Django framework becomes a charm, and will help readers undoubtedly advance their careers. About the Series The Mastering Computer Science covers a wide range of topics, spanning programming languages as well as modern-day technologies and frameworks. The series has a special focus on beginner-level content, and is presented in an easy to understand manner, comprising: Crystal-clear text, spanning various topics sorted by relevance, Special focus on practical exercises, with num

Tags
No tags
ISBN: 1003310494
Publisher: CRC Press
Publish Year: 2022
Language: 英文
Pages: 322
File Format: PDF
File Size: 10.2 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.

(This page has no text content)
Mastering Django Mastering Django helps the reader master the powerful Django framework for Python for creating dynamic applications and projects. Django is a high-level, open-source Python web framework created to help web developers achieve tight deadlines while also meeting a variety of needs. The primary feature of Django that makes it so popular among developers is that it promotes rapid development while providing a consistent and realistic design. Django is a complete toolkit with a basic code and highly adaptable architecture that promotes rapid development – it can shape and pace your web app concept and see it through to launch in a matter of hours. Django’s simplicity, stability, scalability, and flexibility are unmatched. It is currently a vibrant, collaborative, open-source project with thousands of users and contributors. Django is a versatile framework capable of developing any website. Hallmarks of this popular web framework include Robust design, rapid software development, fantastic documentation and tutorials, a vast community with readymade solutions, reasonably easy learning curve, and a high degree of clarity and readability. Django has carved out a niche for itself in the industry over the years, and appropriately so. Many popular apps use Django as their secret ingredient. Django has many features and can accommodate any modern web application. If you wish to build a successful career in web development, learning Django is a wise choice. With Mastering Django, learning the Django framework becomes a charm, and will help readers undoubtedly advance their careers. The Mastering Computer Science series is edited by Sufyan bin Uzayr, a writer and educator with more than a decade of experience in the computing field.
Mastering Computer Science Series Editor: Sufyan bin Uzayr Mastering Django: A Beginner’s Guide Jaskiran Kaur, NT Ozman, and Reza Nafim Mastering Ubuntu: A Beginner’s Guide Jaskiran Kaur, Rubina Salafey, and Shahryar Raz Mastering GNOME: A Beginner’s Guide Jaskiran Kaur, Mathew Rooney, and Reza Nafim Mastering Flutter: A Beginner’s Guide Divya Sachdeva, NT Ozman, and Reza Nafim Mastering Rust: A Beginner’s Guide Divya Sachdeva, Faruq KC, and Aruqqa Khateib Mastering Visual Studio Code: A Beginner’s Guide Jaskiran Kaur, D Nikitenko, and Mathew Rooney For more information about this series, please visit: https://www .rout- ledge .com /Mastering -Computer -Science /book -series /MCS The “Mastering Computer Science” series of books are authored by the Zeba Academy team members, led by Sufyan bin Uzayr. Zeba Academy is an EdTech venture that develops courses and content for learners primarily in STEM fields, and offers education consulting to Universities and Institutions worldwide. For more info, please visit https://zeba.academy
Mastering Django A Beginner’s Guide Edited by Sufyan bin Uzayr
First Edition published 2023 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2023 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publica- tion and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, trans- mitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www .copyright .com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750- 8400. For works that are not available on CCC please contact mpkbookspermissions @tandf .co .uk Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. Library of Congress Cataloging‑in‑Publication Data Names: Bin Uzayr, Sufyan, editor. Title: Mastering Django : a beginner’s guide / edited by Sufyan bin Uzayr. Description: First edition. | Boca Raton, FL : CRC Press, 2023. | Includes bibliographical references and index. Identifiers: LCCN 2022020952 (print) | LCCN 2022020953 (ebook) | ISBN 9781032315997 (hbk) | ISBN 9781032315980 (pbk) | ISBN 9781003310495 (ebk) Subjects: LCSH: Django (Electronic resource) | Web sites--Authoring programs. | Python (Computer program language) Classification: LCC TK5105.8885.D54 M37 2023 (print) | LCC TK5105.8885.D54 (ebook) | DDC 006.7/6--dc23/eng/20220707 LC record available at https://lccn.loc.gov/2022020952 LC ebook record available at https://lccn.loc.gov/2022020953 ISBN: 9781032315997 (hbk) ISBN: 9781032315980 (pbk) ISBN: 9781003310495 (ebk) DOI: 10.1201/9781003310495 Typeset in Minion by Deanta Global Publishing Services, Chennai, India
v Contents Mastering Computer Science Series Preface, xvii About the Editor, xix Chapter 1 ◾ Django’s History 1 WHICH LANGUAGE IS USED IN DJANGO? 1 IS PYTHON NECESSARY FOR DJANGO? 2 WHAT CAN I DO WITH PYTHON? 2 IS PYTHON SUPPORTED? 2 ADVANTAGES OF PYTHON PROGRAMMING LANGUAGE 2 Before Django, Things Needed to Be Done in Python 4 HOW DO WE GET STARTED WITH PYTHON? 12 CODING EDITORS 13 IS PYTHON AN INTERPRETED OR COMPILER LANGUAGE? 13 Applications of Python Programming 13 Additional Features of Python 14 DJANGO 15 WHAT IS A WEB FRAMEWORK? 15 Types of Web Framework 15 Advantages of Using Web Framework for Development? 15 HOW TO USE DJANGO FRAMEWORKS? 16 HOW DOES DJANGO CODE LOOK LIKE? 16 THE MODEL TEMPLATE VIEW (MTV) DESIGN PATTERN 17 WHY DJANGO TEMPLATES? 18 HOW POPULAR IS DJANGO? 18
vi ◾ Contents WHY MTV INSTEAD OF MVC? 18 WHY DJANGO? 18 Advantages of Django 19 Disadvantages of Django 20 DIFFERENCE BETWEEN PROJECT AND APP 21 DJANGO FILE STRUCTURE 21 WHAT ELSE CAN YOU DO? 22 SETTING UP A DATABASE? 22 Main Topics 23 CHAPTER SUMMARY 24 Chapter 2 ◾ Installation 25 SO FIRSTLY, WHAT IS IDE? 25 WHY DO DEVELOPERS USE IDES? 26 UNDERSTANDING THE DIFFERENCES: LOCAL IDE VS. CLOUD IDE 26 What Is a Local IDE? 26 Benefits 26 What Is Cloud IDE? 26 Benefits 27 ARE YOU NEW TO DJANGO? 28 Learning Django 28 Database Driver 28 WHY IS PYTHON REQUIRED? 29 PYTHON INSTALLATION ON WINDOWS 30 HOW TO ADD PATH IN ENVIRONMENT VARIABLE 31 Verifying 32 Python Interpreter 34 WHAT IS A PIP? 36 Installing PIP on Windows 36 PIP Commands 36 SETUP PYTHON VIRTUAL ENVIRONMENT 37 Why Use Virtual Environments? 37
Contents    ◾   vii Organizing Folders 37 Freezing Requirements 37 Command for using the Virtual Environment 40 INSTALLING DJANGO WITH PIP 40 INSTALL DJANGO FROM LOCAL TAR . GZ FILE WITH PIP 42 Install Django from Git 43 INSTALLING AND CREATING THE DJANGO PROJECT 43 HOW TO CHANGE THE DEFAULT PORT? 45 HOW TO CHECK THE DJANGO VERSION? 46 Template File 47 CREATING A PROJECT AND DEPLOYING 48 Deploying with Heroku 48 CHAPTER SUMMARY 49 Chapter 3 ◾ File Structure 51 EXAMINING THE PROJECT STRUCTURE AND APPS 51 EXPLORING THE PROJECT FOLDER 52 Manage . py 53 Middleware 54 Types of Middleware 55 Custom Middleware 56 How to Create Middleware? 56 Middleware Methods 57 urls . py 57 URL Mapping 57 Most Commonly Used Django URL Functions 58 views . py 58 wsgi . py 60 asgi . py 60 EXPLORING THE APP FOLDER 60 Migration Folder 62 models . py 62
viii ◾ Contents urls . py 62 tests . py 62 Files and Directories to Create 63 DJANGO COMMANDS 63 Create a Project’s Directory Structure 63 Create New App in Project 63 Run the Server 63 Create Database Migration 63 Migrate the Database 64 Create Admin User 64 Create Admin User Git Bash 64 DJANGO IS A LOOSELY COUPLED FRAMEWORK 64 Django's URL Configuration 64 ADDITIONAL CONFIGURATION 64 URL Dispatcher 69 CHAPTER SUMMARY 70 Chapter 4 ◾ Django’s Model 71 FUNDAMENTALS OF DJANGO’S MODEL 71 Different Types of Fields 74 HOW DO DJANGO MODELS WORK? 76 What Is Fields Option? 76 Field Options 77 Explanation 77 Adding Model String 80 What Is Unicode Object? 80 Magic method or Dunder Method 80 RELATIONSHIPS AND QUERY SET 85 Relationships 85 Many-to-Many Relationships 85 Retrieving Single Object from QuerySets 86 Filtering the Records 87
Contents    ◾   ix Using exclude() Method 87 Ordering Data 87 Chaining Lookups 88 Slicing Data 88 Many-to-One Relationships 89 SOME IMPORTANT FIELD LOOKUPS 90 One-to-One Relationships 91 WHY DO WE USE MODELS? 93 CONFIGURING THE DATABASE 93 Types of Database 93 Connecting to Database 94 Modelformsets 95 THE ADMIN MODULE 95 Installing the Admin Module 95 CHAPTER SUMMARY 96 Chapter 5 ◾ Django’s View 97 VIEWS IN DJANGO 97 CONFIGURATION OF THE URLS 98 MAPPING URLS TO VIEWS 99 HOW DOES IT PROCESS A REQUEST? 99 WHAT IS URL ROUTING? 100 WHAT IS PATH VS. RE_PATH? 101 How to Create Views 104 Adding a Homepage Path 104 Function-Based Views 105 Class-Based Views 105 WHAT ARE GENERIC VIEWS? 106 Types of Generic View 106 Django View HTTP Decorators 107 URLconfs and Loose Coupling 108 Django Exceptions and Error-Handling 108
x ◾ Contents WHAT ARE EXCEPTIONS? 109 Exception in Python 109 WHY PRACTICE EXCEPTIONS? 110 Common Exception 110 Explanation 111 Raising Exceptions 111 Custom Exceptions 111 Django Exceptions 112 URL Resolver Exceptions 115 ADVANCED VIEW AND URLS 116 Using Named Groups 117 Keyword Arguments vs. Positional Arguments 117 Passing Extra Options to View Functions 117 CHAPTER SUMMARY 118 Chapter 6 ◾ Django’s Templates 119 BASICS OF TEMPLATE 119 JINJA 120 Why Is Jinja2 Useful? 120 Origin of Jinja2? 120 API 120 Why do we need Jinja2? 121 Installation 121 Dependencies 121 WHAT IS BABEL? 122 Template 122 Django Template System Basic 124 Operators 126 Other Operators 126 Python in-built Method 127 Various Functions 127 Comparisons 129
Contents    ◾   xi Logic 130 Rendering a Template 130 The Django Template Language 131 WHY DO WE USE ENGINE? 132 WHAT ARE LOADERS? 132 Support for Template Engines 133 Configuration or How Django Finds the Templates? 133 Common terms used in TEMPLATE 133 Creating a Site Template 133 Addition Path for Template 134 Full Example of Templates 134 Class Jinja2 135 Usage of Template Loaders 135 Optional Argument 136 Template Inheritance 136 Django Static Files Handling 138 CHAPTER SUMMARY 140 Chapter 7 ◾ Django’s Admin Panel 141 OVERVIEW OF DJANGO ADMIN 141 ACCESSING THE DJANGO ADMIN SITE 142 Enabling Admin Panel 144 WHAT DOES ADMIN DO? 144 HOW DOES IT WORK? 145 HOW SECURE IS DJANGO ADMIN? 145 Writing Action Functions 145 Usage 145 Various Subcommands 146 Django Admin Customization 147 Python manage . py Startapp Products 147 How to Register/Unregister Models from Admin? 149 Customization of Heading in Admin Panel 149
xii ◾ Contents Django Admin Custom Page Layout, Data, and Behaviors 149 Model Admin Classes 150 HOW TO ADD JQUERY IN YOU PROJECT? 155 CHAPTER SUMMARY 159 Chapter 8 ◾ Django’s Forms 161 HTML FORMS 161 Link to a Page with the Form 162 Input Tag 163 Django’s Role in Forms 163 Django’s Forms 163 forms.Form vs forms.ModelForm 164 The Django Form Class 164 Bound and Unbound Form Instances 164 Widgets 165 The form class 165 Widgets Argument 167 Django-crispy-Forms 171 How to Use Django Crispy Forms 171 Crispy Filter 172 Installation 172 Load in the Crispy Form Tags 173 Using the Django as_crispy_field Form Filter 174 WHAT TO DO WHEN THE CRISPY FORM IS NOT WORKING? 174 Template Packs 174 How to Style Django Forms with Bootstrap 175 Form Helpers 176 Django UserCreationForm 176 Implement Django UserCreationForm 176 THE REASON WHY WE USE SELF.CLEANED_DATA 178 Understanding Args and Kwargs in Python 178 What Are Args? 178
Contents    ◾   xiii What Are Kwargs? 179 Use of Args and Kwargs 179 Using Both Args and Kwargs in a Function 179 CHAPTER SUMMARY 179 Chapter 9 ◾ The Advanced Model 181 DJANGO MODEL DEFINITION 181 Fields 182 Common Field Arguments 182 Fields for Common Data Types 183 Importing the model . py in Various Files 184 Various Advanced Topics in Django Models 184 Model Method 185 Creating New Instances 185 Customizing Model Loading 185 Deleting Objects from Database 186 Model.get_deferred_fields() 186 Validating Objects 186 Model.clean_fields(exclude=None) 186 Model.validate_unique(exclude=None) 186 Saving Objects 186 Auto-incrementing Primary Keys 186 Model . pk vs Model . id 186 Model Objects 187 Saving ForeignKey and ManyToManyField Fields 187 Retrieving All Objects 188 Other model instance methods 189 UserModel 190 User Model Built-in Fields 191 Methods 192 Logout and Login Signals 192 Manager Methods 193 Model Manager 193
xiv ◾ Contents A Custom Name to the Default Manager 193 How to Use the Student Manager 193 Methods of Manager Class 194 CHAPTER SUMMARY 194 Chapter 10 ◾ Deployment 195 INTRODUCTION 195 Prerequisites 195 What Is a Deployment Environment? 196 PYTHON INSTALLATION ON WINDOWS 196 How to Add PATH in Environment Variable 197 INSTALLING DJANGO WITH PIP 197 Creation of the Django Project 199 CHOOSING THE RIGHT HOSTING PROVIDER 199 Ready to Publish Your Website 200 DJANGO DEPLOYMENT INTERFACES 201 WSGI 201 ASGI 203 class Application 203 AWS? 204 What Is Cloud Computing? 204 Types of Clouds 204 Cloud Services Models 204 AWS SERVICES 205 AWS ELASTIC BEANSTALK 206 Benefits 206 Open the ES environment in the browser 211 Accessing Django Admin in Deployment 211 Collect the Static in the CLI 211 Check the Django Web App from AWS 212 AZURE 212 Features of Cloud-Based Services 212
Contents    ◾   xv Microsoft Azure Features Related to Mobile Services 213 DEPLOYING OUR DJANGO APP ONTO AZURE 214 File Structure 214 Installing Azure 215 Azure Deployment Files 218 GIT 218 CHAPTER SUMMARY 219 Chapter 11 ◾ Create Quiz Web App with Python Django 221 REACT, FLASK, RUBY ON RAILS, ETC. 221 HOW TO CREATE A QUIZ LIST APP IN PYTHON DJANGO 222 Purpose 222 Project Prerequisites 222 Virtual Environment 222 Changing in Our Models 225 Making a Migration 226 Migrating to the Database 226 Registering to the Admin 227 Creating Superuser and Viewing in the Admin Panel 227 Making and Changing the Templates 228 BASE .HT ML 229 LOGIN .HT ML 230 LOGIN PAGE 231 REGISTER PAGE 232 HOME PAGE 235 RESULT PAGE 238 url . py 238 url . py 239 form . py 240 view . py 241 app . py 245 WHAT IS THE PURPOSE OF THIS PROJECT? 245
xvi ◾ Contents Chapter 12 ◾ Project To-Do List 247 REACT, FLASK, RUBY ON RAILS, ETC. 247 HOW TO CREATE A TO-DO LIST APP IN PYTHON DJANGO 248 Creating Superuser and Viewing in the Admin Panel 250 Making a Migration 250 Migrating to the Database 250 Edit Page 254 After Edit Page 254 Login Page 256 Register Page 257 Show Details Page 259 Views . py 259 urls . py 264 model . py 265 forms . py 266 Apps . py 267 admin . py 267 In admin . py 268 Chapter 13 ◾ Comparative Study between Django, Flask, Node.Js, and Spring Boot 271 TYPES OF PYTHON FRAMEWORK 272 WHAT IS FLASK? 272 DJANGO VS NODE . JS 275 What Is Node .j s? 275 DJANGO VS. SPRING BOOT 277 What Is Spring Boot? 277 CHAPTER SUMMARY 278 APPRAISAL, 279 BIBLIOGRAPHY, 285 INDEX, 291
xvii Mastering Computer Science Series Preface The Mastering Computer Science covers a wide range of topics, spanning programming languages as well as modern-day technolo- gies and frameworks. The series has a special focus on beginner-level con- tent, and is presented in an easy-to-understand manner, comprising: • Crystal-clear text, spanning various topics sorted by relevance • A special focus on practical exercises, with numerous code samples and programs • A guided approach to programming, with step-by-step tutorials for the absolute beginners • Keen emphasis on real-world utility of skills, thereby cutting the redundant and seldom-used concepts and focusing instead of indus- try-prevalent coding paradigm • A wide range of references and resources to help both beginner and intermediate-level developers gain the most out of the books The Mastering Computer Science series of books start from the core con- cepts, and then quickly move on to industry-standard coding practices, to help learners gain efficient and crucial skills in as little time as possible. The books assume no prior knowledge of coding, so even the absolute newbie coders can benefit from this series. The Mastering Computer Science series is edited by Sufyan bin Uzayr, a writer and educator with more than a decade of experience in the comput- ing field.
(This page has no text content)
xix About the Editor Sufyan bin Uzayr is a writer, coder, and entrepreneur with more than a decade of experience in the industry. He has authored several books in the past, pertaining to a diverse range of topics, ranging from History to Computers/IT. Sufyan is the Director of Parakozm, a multinational IT company spe- cializing in EdTech solutions. He also runs Zeba Academy, an online learning and teaching vertical with a focus on STEM fields. Sufyan specializes in a wide variety of technologies, such as JavaScript, Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees, including ones in Management, IT, Literature, and Political Science. Sufyan is a digital nomad, dividing his time between four countries. He has lived and taught in universities and educational institutions around the globe. Sufyan takes a keen interest in technology, politics, literature, history, and sports, and in his spare time, he enjoys teaching coding and English to young students. Learn more at sufyanism .co m.