Django in Action Год издания: 2024 Автор: Trudeau Christopher Издательство: Manning Publications Co. ISBN: 978-1633-43816-3 Язык: Английский Формат: PDF Качество: Издательский макет или текст (eBook) Интерактивное оглавление: Да Количество страниц: 438 Описание: Build professional quality web applications using Python and the Django 5.0 web framework. The Django web application framework powers huge sites like Netflix, Dropbox, YouTube, and Spotify. Learn how it can power your web apps too! In this hands-on book, you'll begin building a fully functional web application with Django starting with chapter 1. In Django in Action you'll: Build a multi-user web site in Django Read, write, and manage data Create reusable and composable HTML templates Manage user data including form submissions and file uploads Set up authentication, authorization, and per-person-per-page permissions Manage the backend using the Django Admin tool Discover Django libraries and plugins Django in Action is the perfect way to get started for new Django developers creating their first Python-based web apps. It's written by Christopher Trudeau, co-host of The Real Python Podcast and creator of dozens of popular courses at Real Python and TalkPython. The book starts with Django's basics and works through all of the core concepts of the framework until you're comfortable and confident creating your own web apps. You'll especially enjoy the author's lighthearted style that makes learning fun! Foreword by Michael Kennedy. About the technology: Django makes life easier for Python web developers. This "batteries included" framework comes packed with everything you need—a template engine that crafts HTML-like code, efficient user management features, automated testing, robust API support, and much more. If you know the basics of Python, Django will help you build professional-quality web applications. This book will show you how. About the book: InDjango in Action you'll dive deep into Django as you build a complete multi-user website. Hands-on from the start, each chapter introduces new features to your site, including password management and authentication, web forms and file uploads, and dynamic, jаvascript-like interactivity. You'll see how all the components of a Django project come together while learning practical tips on leveraging third-party libraries and deploying your code to production. What's inside: Reusable and composable HTML templates Reading, writing, and managing data Backend management with Django Admin Exploring Django libraries and plugins About the reader: For readers with basic Python programming and some HTML knowledge. About the author: Christopher Trudeau is the co-host of the Real Python Podcast, a prolific author of Django and Python articles and video courses, and an experienced Python developer. Создавайте веб-приложения профессионального качества, используя Python и веб-платформу Django 5.0. Платформа веб-приложений Django поддерживает такие крупные сайты, как Netflix, Dropbox, YouTube и Spotify. Узнайте, как она может улучшить и ваши веб-приложения! В этой практической книге вы начнете создавать полнофункциональное веб-приложение на Django, начиная с главы 1. В Django in Action вы узнаете: Как создать многопользовательский веб-сайт на Django Как читать, записывать и управлять данными Как создавать повторно используемые и компонуемые HTML-шаблоны Управление пользовательскими данными, включая отправку формуляров и загрузку файлов Настройте аутентификацию, авторизацию и разрешения для каждого пользователя на странице Управляйте серверной частью с помощью инструмента администрирования Django Откройте для себя библиотеки и плагины Django Django in Action - это идеальный способ начать работу для начинающих разработчиков Django, создающих свои первые веб-приложения на основе Python. Он написан Кристофером Трюдо, соведущим подкаста Real Python и создателем десятков популярных курсов в Real Python и TalkPython. Книга начинается с основ Django и проходит через все основные концепции фреймворка, пока вы не почувствуете себя комфортно и уверенно при создании собственных веб-приложений. Вам особенно понравится беззаботный стиль автора, который делает обучение увлекательным! Предисловие Майкла Кеннеди. О технологии: Django упрощает жизнь веб-разработчикам на Python. Этот фреймворк "с батарейками" оснащен всем необходимым — движком шаблонов, который создает HTML-подобный код, эффективными функциями управления пользователями, автоматизированным тестированием, надежной поддержкой API и многим другим. Если вы знакомы с основами Python, Django поможет вам создавать веб-приложения профессионального качества. Из этой книги вы узнаете, как это сделать. О книге: InDjango в действии вы глубоко погрузитесь в Django при создании полноценного многопользовательского веб-сайта. С самого начала каждая глава знакомит вас с новыми функциями вашего сайта, включая управление паролями и аутентификацию, веб-формы и загрузку файлов, а также динамическую интерактивность, подобную javascript. Вы увидите, как все компоненты проекта Django сочетаются друг с другом, а также узнаете практические советы по использованию сторонних библиотек и развертыванию вашего кода в рабочей среде. Что внутри: Многоразовые и компонуемые HTML-шаблоны Чтение, запись и управление данными Управление серверной частью с помощью Django Admin. Знакомство с библиотеками и плагинами Django О читателе: Для читателей, владеющих основами программирования на Python и некоторыми знаниями HTML. Об авторе: Кристофер Трюдо - соведущий подкаста The Real Python, плодовитый автор статей и видеокурсов по Django и Python, а также опытный разработчик Python.
Примеры страниц (скриншоты)
Оглавление
foreword xi preface xiii acknowledgments xv about this book xvii about the author xxi about the cover illustration xxii PART 1 DJANGO ESSENTIAL 1 1 Django unfolds 3 1.1 Django’s parts 4 Mapping URLs, Django views, and the MVC model 8 Databases: Dynamic sites need data 11 ■ Structuring HTML for reuse 13 ■ Multiuser sites 15 1.2 What can you do with Django? 15 Server-side, single-page, and mixed-page applications 16 When and where you should use it 17 ■ Potential projects 18 The RiffMates project 19 2 Your first Django site 21 2.1 The RiffMates project 21 2.2 Creating a Django project 22 2.3 Projects vs. apps 29 2.4 Your first Django app 32 2.5 Your first Django view 33 2.6 Registering a route 36 2.7 Visiting your view 37 2.8 Exercises 38 3 Templates 40 3.1 Where to use templates 40 3.2 Context objects and the parts of a Template 41 3.3 Django shell 43 3.4 Rendering a Template 43 3.5 Common tags and filters 46 Conditional blocks 46 ■ Looping blocks 47 ■ Comment blocks 49 ■ Verbatim blocks 49 ■ Referencing URLs 50 Common filters 51 3.6 Using render() in a view 51 3.7 Escaping special characters 56 3.8 Composing templates out of blocks 59 Writing a base template file 60 ■ Including an HTML snippet 62 3.9 Exercises 63 4 Django ORM 65 4.1 Interacting with a database 65 4.2 ORM Models 68 4.3 SQLite and dbshell 71 4.4 Model queries 73 Using .all() and .filter() to fetch QuerySet results 75 Field look-ups 77 4.5 Modifying your data 79 4.6 Querying models in views 81 Using URL arguments 81 ■ Listing pages 86 ■ Using query parameters for pagination 87 4.7 Model relations 89 One-to-many relationships 90 ■ Many-to-many relationships 94 4.8 Model fields 97 Popular cross-field field options 97 ■ Popular fields 98 4.9 Fixtures 99 4.10 Danger zone, or know thy SQL 103 4.11 Exercises 103 5 Django Admin 105 5.1 Touring the Django Admin 105 Creating an admin user 107 ■ The default Django Admin 108 Adding your own models 109 5.2 Customizing a listing page 113 Sorting and searching 114 ■ Filtering 115 ■ New in Django 5: Facets 119 5.3 Cross-linking between related objects 119 5.4 Model Meta properties 122 Sort order 122 ■ Indexes 122 ■ Uniqueness 123 Object names 124 5.5 Exercises 124 PART 2 DJANGO BUILDING BLOCKS 127 6 User management 129 6.1 Multiuser websites 129 6.2 Storing user data 131 Choosing a user account mechanism 131 ■ Adding a user profile 134 6.3 Restricting access to views 137 6.4 Authorization in views 139 Handling logouts 141 6.5 Using signals to automatically create a user profile 142 6.6 Password management 145 Password reset page 146 ■ Password reset email 147 New password form 149 6.7 Exercises 150 7 Forms, user data, static files, and uploads 152 7.1 Web forms 153 Handling GET and POST in views 155 ■ CSRF 160 Beautifying web forms 160 ■ New in Django 5: Reusable field group templates 161 7.2 Django ModelForm 162 Validating fields in a model 162 ■ A ModelAdmin for SeekingAd using Truncate 165 ■ Writing a ModelForm 166 Using SeekingAdForm in a view 169 ■ Editing existing data with forms 172 7.3 Serving static files 175 7.4 Uploads 178 Configuring your project for uploads 178 ■ Storing and referencing uploaded files 180 ■ File upload forms and views 183 ■ Restricted file downloads 188 7.5 Exercises 188 8 Testing your project 191 8.1 Automated testing 191 The scope of tests 192 ■ Automated testing in Python 194 8.2 Your first Django test 194 8.3 Testing with the database 197 8.4 Expecting errors 201 8.5 Authenticating and posting data 202 8.6 Testing with file uploads 206 8.7 More testing techniques 207 LiveServerTestCase for Selenium 208 ■ Third-party helpers 208 8.8 Measuring tests and code quality 209 8.9 Exercises 210 9 Management commands 213 9.1 Management commands in practice 213 Built-in management commands 214 ■ Changing a password 216 ■ Configuration 217 ■ Flushing the database 217 ■ SQL commands 218 9.2 Writing your own management command 219 9.3 Handling arguments 222 Built-in arguments 227 9.4 Testing, and using STDOUT and STDERR 228 9.5 Exercises 229 10 Migration 232 10.1 Migration scripts in detail 232 An initial migration 234 ■ Changing a model 236 10.2 Migration with existing data 238 10.3 Squashing a migration 243 10.4 More migration choices 245 10.5 Exercises 248 PART 3 DJANGO PROJECTS 251 11 APIs 253 11.1 Why use an API? 253 CRUD and REST 255 ■ Versioning an API 258 11.2 Building an API with Django Ninja 258 Serializing objects 261 ■ Handling arguments 264 Filtering your listings 268 ■ Nesting data 271 Authenticating your API 272 ■ Creating objects with the API 274 ■ Updating and deleting with the API 277 11.3 Other API libraries 279 11.4 Exercises 281 12 Making your pages more dynamic with HTMX 283 12.1 Dynamic web pages 283 12.2 HTMX attributes 284 12.3 Lazy loading 286 12.4 Search-as-you-type with infinite scroll 288 12.5 Click to edit 295 12.6 Exercises 299 13 Django power tools 301 13.1 Django Debug Toolbar 302 13.2 Tool libraries 304 Django Extensions 305 ■ Django Awl 305 13.3 Look and feel 307 Django Grappelli 307 ■ Crispy forms 307 ■ Favicons 309 13.4 Feature flags 310 13.5 Static sites 311 14 Where to go next 315 14.1 Within Django 315 14.2 Configuration 317 14.3 Dealing with data 318 14.4 Web tools 319 14.5 Asynchronous actions 320 14.6 A wide world 321 appendix A Installation and setup 323 appendix B Django in a production environment 330 appendix C Django template tag and filter reference 347 appendix D Django ORM field reference 357 appendix E Sample exercise solutions 364 index 401
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum