Web Development with Django: A definitive guide to building modern Python web applications using Django 4, 2nd Edition / Веб-разработка с помощью Django: Полное руководство по созданию современных веб-приложений на Python с использованием Django 4, 2-е издание Год издания: 2023 Автор: Shaw Ben and others / Шоу Бен и другие Издательство: Packt Publishing ISBN: 978-1-80323-060-3 Язык: Английский Формат: PDF, EPUB Качество: Издательский макет или текст (eBook) Интерактивное оглавление: Да Количество страниц: 764 Описание: Work through realistic case studies to create your own websites easily, securely, and quickly Key Features Understand Django functionality and the Model-View-Template (MVT) paradigm Create and iteratively build a book review website, adding features as you build your knowledge Explore advanced concepts such as REST API implementation and third-party module integration Book Description Do you want to develop reliable and secure applications that stand out from the crowd without spending hours on boilerplate code? You’ve made the right choice trusting the Django framework, and this book will tell you why. Often referred to as a “batteries included” web development framework, Django comes with all the core features needed to build a standalone application. Web Development with Django will take you through all the essential concepts and help you explore its power to build real-world applications using Python. Throughout the book, you’ll get the grips with the major features of Django by building a website called Bookr – a repository for book reviews. This end-to-end case study is split into a series of bitesize projects presented as exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. As you advance, you’ll acquire various practical skills, including how to serve static files to add CSS, JavaScript, and images to your application, how to implement forms to accept user input, and how to manage sessions to ensure a reliable user experience. You’ll cover everyday tasks that are part of the development cycle of a real-world web application. By the end of this Django book, you’ll have the skills and confidence to creatively develop and deploy your own projects. What you will learn Create a new application and add models to describe your data Use views and templates to control behavior and appearance Implement access control through authentication and permissions Develop practical web forms to add features such as file uploads Build a RESTful API and JavaScript code that communicates with it Connect to a database such as PostgreSQL Who this book is for This book is for programmers looking to enhance their web development skills using the Django framework. To fully understand the concepts explained in this book, basic knowledge of Python programming as well as familiarity with JavaScript, HTML, and CSS is assumed. Работайте с помощью реалистичных тематических исследований, чтобы создавать свои собственные веб-сайты легко, безопасно и быстро Ключевые функции Понимать функциональность Django и парадигму Model-View-Template (MVT) Последовательно создавайте веб-сайт с обзорами книг, добавляя функции по мере накопления знаний Изучите передовые концепции, такие как реализация REST API и интеграция сторонних модулей Описание книги Вы хотите разрабатывать надежные и безопасные приложения, которые выделяются из общей массы, не тратя часы на написание шаблонного кода? Вы сделали правильный выбор, доверившись фреймворку Django, и эта книга расскажет вам почему. Часто называемый фреймворком веб-разработки “с батарейками в комплекте”, Django поставляется со всеми основными функциями, необходимыми для создания автономного приложения. Веб-разработка с помощью Django познакомит вас со всеми основными концепциями и поможет изучить его возможности для создания реальных приложений с использованием Python. На протяжении всей книги вы будете знакомиться с основными функциями Django, создав веб–сайт под названием Bookr - хранилище рецензий на книги. Это комплексное тематическое исследование разделено на серию небольших проектов, представленных в виде упражнений и активностей, что позволяет вам бросить вызов самому себе приятным и достижимым способом. По мере продвижения вы приобретете различные практические навыки, в том числе, как использовать статические файлы для добавления CSS, JavaScript и изображений в ваше приложение, как внедрять формы для приема пользовательского ввода и как управлять сеансами для обеспечения надежного взаимодействия с пользователем. Вы расскажете о повседневных задачах, которые являются частью цикла разработки реального веб-приложения. К концу этой книги по Django у вас появятся навыки и уверенность, необходимые для творческой разработки и внедрения ваших собственных проектов. Чему вы научитесь Создадите новое приложение и добавите модели для описания ваших данных Использовать представления и шаблоны для управления поведением и внешним видом Реализуете контроль доступа с помощью аутентификации и разрешений Разработаете практичные веб-формы для добавления таких функций, как загрузка файлов Создадите RESTful API и JavaScript-код, который взаимодействует с ним Подключитесь к базе данных, такой как PostgreSQL Для кого предназначена эта книга Эта книга предназначена для программистов, желающих улучшить свои навыки веб-разработки с использованием фреймворка Django. Чтобы полностью понять концепции, описанные в этой книге, требуются базовые знания программирования на Python, а также знакомство с JavaScript, HTML и CSS.
Примеры страниц
Оглавление
Prefacexvii 1 An Introduction to Django1 Technical requirements 2 Scaffolding a Django project and app 2 Exercise 1.01 – creating a project and app, and starting the development server 4 Understanding the model-view-template paradigm 7 Models7 Views8 Templates8 MVT in practice 8 An introduction to HTTP 11 Processing a request 15 Exploring the Django project structure 16 The myproject directory 18 Django development server 19 Django apps 19 PyCharm setup 21 Exercise 1.02 – project setup in PyCharm 21 Introducing Django views 30 Exploring URL mapping detail 31 Exercise 1.03 – writing a view and mapping a URL to it 32 Working with GET, POST, and QueryDict objects 36 Exercise 1.04 – exploring GET values and QueryDict objects 38 Exploring Django settings 40 Referring to Django Settings in Your Code 42 Finding HTML templates in app directories43 Exercise 1.05 – creating a templates directory and a base template 43 Rendering a template with the render function 47 Exercise 1.06 – rendering a template in a view 47 Rendering variables in templates 49 Exercise 1.07 – using variables in templates 49 Debugging and dealing with errors 52 Exceptions52 Exercise 1.08 – generating and viewing exceptions54 Debugging55 Exercise 1.09 – debugging your code 56 Activity 1.01 – creating a site welcome screen 60 Table of Contents Activity 1.02 – a book search scaffold 61 Summary 63 2 Models and Migrations 65 Technical requirements 66 Understanding and using databases 66 Relational databases 67 Non-relational databases 67 Database operations using SQL 68 Data types in relational databases 68 Exercise 2.01 – creating a book database 68 Understanding CRUD operations using SQL 72 SQL create operations 73 SQL read operations 73 SQL update operations 74 SQL delete Operations 75 Exploring Django ORM 75 Database configuration and creating Django applications 76 Django apps 77 Django migration 78 Creating Django models and migrations 80 Field options 82 Primary keys 84 Relationships 86 Adding the Review model 90 Model methods 92 Migrating the reviews app 93 Django’s database CRUD operations 95 Exercise 2.02 – creating an entry in the bookr database 96 Exercise 2.03 – using the create() method to create an entry 97 Creating an object with a foreign key 98 Exercise 2.04 – creating records for a many-to-one relationship 98 Exercise 2.05 – creating records with many-to-many relationships 100 Exercise 2.06 – a many-to-many relationship using the add() method 101 Using the create() and set() methods for many-to-many relationships 102 Read operations 103 Exercise 2.07 – using the get() method to retrieve an object 103 Returning an object using the get() method 104 Exercise 2.08 – using the all() method to retrieve a set of objects 105 Retrieving objects by filtering 105 Exercise 2.09 – using the filter() method to retrieve objects 106 Filtering by field lookups 106 Using pattern matching for filtering operations 107 Retrieving objects by using the exclude() method 108 Retrieving objects using the order_by() method 108 Querying across relationships 111 Querying using foreign keys 111 Querying using the model name 111 Querying across foreign key relationships using the object instance 112 Exercise 2.10 – querying across a many-tomany relationship using the field lookup 112 Exercise 2.11 – a many-to-many query using objects 113 Exercise 2.12 – a many-to-many query using the set() method 113 Exercise 2.13 – using the update() method 114 Exercise 2.14 – using the delete() method 115 Bulk create and bulk update operations 115 Exercise 2.15 – creating multiple records using bulk_create 116 Exercise 2.16 – updating multiple records using bulk_update 117 Performing complex lookups using Q objects 117 Exercise 2.17 – performing a complex query using a Q object 118 Exercise 2.18 – verifying whether a queryset contains a given object 118 Activity 2.01 – creating models for a project management application 120 Populating the Bookr project’s database 120 Summary 121 3 URL Mapping, Views, and Templates 123 Technical requirements 124 Understanding function-based views 124 Understanding class-based views 124 URL configuration 125 Exercise 3.01 – implementing a simple function-based view 127 Working with Django templates 130 Exercise 3.02 – using templates to display a greeting message 132 Django’s template language 134 Exercise 3.03 – displaying a list of books and reviews 136 Template inheritance 139 Template styling with Bootstrap 140 Exercise 3.04 – adding template inheritance and a Bootstrap navigation bar 142 Activity 3.01 – implementing the book details view 144 Summary 146 4 An Introduction to Django Admin 147 Technical requirements 149 Creating a superuser account 149 Exercise 4.01 – creating a superuser account 149 CRUD operations using the Django admin app 151 Create 152 Retrieve 154 Update 156 Delete 158 Managing Django users and groups 159 Exercise 4.02 – adding and modifying users and groups through the admin app 160 Registering models with the admin app 165 Registering the reviews model 166 Change lists 167 The Change publisher page 168 The Book change page 172 Exercise 4.03 – foreign keys and deletion behavior in the admin app 175 Customizing the admin interface 177 Site-wide Django admin customizations 177 Customizing the ModelAdmin classes 187 The list display fields 188 The display decorator 194 The filter 195 Exercise 4.04 – adding the date list_filter and date_hierarchy filters 196 The search bar 199 Excluding and grouping fields 202 Activity 4.03 – customizing the Model admins 206 Summary 209 5 Serving Static Files 211 Technical requirements 213 Static file serving 213 Introduction to Static Files Finder 214 Static file finders – use during a request 215 AppDirectoriesFinder 215 Static file namespacing 216 Exercise 5.01 – serving a file from an app directory 218 Generating static URLs with the static template tag 222 Exercise 5.02 – using the static template tag 226 FileSystemFinder 229 Exercise 5.03 – serving from a project static directory 230 Static file finders – use during collectstatic 233 Exercise 5.04 – collecting static files for production 235 STATICFILES_DIRS prefixed mode 236 The findstatic command 239 Exercise 5.05 – finding files using findstatic 240 Serving the latest files (for cache invalidation) 243 Exercise 5.06 – exploring the ManifestFilesStorage storage engine 245 Custom storage engines 249 Activity 5.01 – adding a Reviews logo 252 Activity 5.02 – CSS enhancements 254 Activity 5.03 – adding a global logo 256 Summary 258 6 Forms 259 Technical requirements 259 What is a form? 260 The form element 262 Types of inputs 263 Exercise 6.01 – building a form in HTML 264 Form security with Cross-Site Request Forgery Protection 272 Accessing data in the View 276 Exercise 6.02 – working with POST data in a view 276 Choosing between GET or POST 280 Why use GET when we can put parameters in the URL mappings? 282 The Django Forms library 283 Defining a form 284 Rendering a form in a template 295 Exercise 6.03 – building and rendering a Django form 300 Validating forms and retrieving Python values 305 Exercise 6.04 – validating forms in a view 308 Built-in field validation 311 Exercise 6.05 – adding extra field validation 312 Activity 1 – Book Search 314 Summary 318 7 Advanced Form Validation and Model Forms 319 Technical requirements 320 Custom field validation and cleaning 320 Custom validators 320 Cleaning methods 322 Multi-field validation 323 Exercise 7.01 – custom clean and validation methods 327 Adding placeholders and initial values 336 Exercise 7.02 – placeholders and initial values 338 Creating or editing Django models 340 The ModelForm class 342 Exercise 7.03 – creating and editing a publisher 346 Activity 7.01 – styling and integrating the publisher form 352 Activity 7.02 – Review Creation UI 356 Summary 363 8 Media Serving and File Uploads 365 Technical requirements 366 Settings for media uploads and serving 366 Serving media files in development 366 Exercise 8.01 – configuring media storage and serving 367 Context processors and using MEDIA_URL in templates 371 Exercise 8.02 – template settings and using MEDIA_URL in templates 373 File uploads using HTML forms 376 Working with uploaded files in a view 378 Exercise 8.03 – file upload and download 381 File uploads with Django forms 385 Exercise 8.04 – file uploads with a Django form 386 Image uploads with Django forms 391 Resizing an image with Pillow 393 Exercise 8.05 – image uploads using Django forms 394 Serving uploaded (and other) files using Django 397 Storing files on model instances 398 Storing images on model instances 402 Working with FieldFile 403 Referring to media in templates 408 ModelForms and file uploads 414 Exercise 8.07 – file and image uploads using ModelForm 416 Handling file saving 419 Activity 8.01 – image and PDF upload of books 421 Activity 8.02 – displaying the cover and sample link 425 Summary 427 9 Sessions and Authentication 429 Technical requirements 430 Middleware 430 Middleware modules 431 Implementing authentication views and templates 433 Exercise 9.01 – repurposing the Admin app login template 438 Password storage in Django 441 The profile page and the request.user object 441 Exercise 9.02 – adding a profile page 442 Authentication decorators and redirection 444 Exercise 9.03 – adding authentication decorators to the views 447 Enhancing templates with authentication data 450 Exercise 9.04 – toggling login and logout links in the base template 450 Activity 9.01 – authentication-based content using conditional blocks in templates 452 Sessions 454 The session engine 454 Do you need to flag cookie content? 455 Pickle or JSON storage? 456 Exercise 9.05 – examining the session key 457 Storing data in sessions 461 Exercise 9.06 – storing recently viewed books in sessions 462 Activity 9.02 – using session storage for the Book Search page 467 Summary 469 10 Advanced Django Admin and Customizations 471 Technical requirements 472 Customizing the admin site 472 Discovering admin files in Django 472 Django’s AdminSite class 473 Exercise 10.01 – creating a custom admin site for Bookr 475 Overriding the default admin.site 478 Exercise 10.02 – overriding the default admin site 478 Customizing admin site text using AdminSite attributes 480 Customizing admin site templates 481 Exercise 10.03 – customizing the logout template for the Bookr admin site 483 Adding views to the admin site 485 Creating the view function 485 Accessing common template variables 486 Mapping URLs for the custom view 486 Restricting custom views to the admin site 487 Exercise 10.04 – adding custom views to the admin site 488 Passing additional keys to templates using template variables 491 Activity 10.01 – building a custom admin dashboard with a built-in search 492 Summary 494 11 Advanced Templating and Class-Based Views 495 Technical requirements 496 Template filters 496 Custom template filters 497 Creating custom template filters 498 Implementing the custom filter function 499 Using custom filters inside templates 499 Exercise 11.01 – Creating a custom template filter 500 String filters 503 Template tags 504 The types of template tags 505 Simple tags 505 Creating a simple template tag 505 Exercise 11.02 – Creating a custom simple tag 507 Inclusion tags 510 Exercise 11.03 – Building a custom inclusion tag 512 Django views 515 Class-based views 515 Exercise 11.04 – Creating a book catalog using a CBV 517 CRUD operations with CBVs 523 The Read view 524 Activity 11.01 – Rendering details on the user profile page using inclusion tags 528 Summary 530 12 Building a REST API 531 Technical requirements 532 Understanding REST APIs 532 Django REST framework 532 Installation and configuration 533 Functional API views 533 Understanding serializers 536 Class-based API views and generic views 539 Activity 12.01 – creating an API endpoint for a top contributors page 544 Simplifying the code using ViewSets 545 URL configuration using routers and Viewsets 546 Exercise 12.04 – using ViewSets and routers 546 Implementing authentication 550 Token-based authentication 551 Exercise 12.05 – omplementing token-based authentication for Bookr APIs 551 Summary 556 13 Generating CSV, PDF, and Other Binary Files 557 Technical requirements 558 Working with CSV files inside Python 558 Working with Python’s csv module 558 Reading data from a CSV file 558 Exercise 13.0 – reading a CSV file with Python 559 Writing to CSV files using Python 562 Exercise 13.02 – generating a CSV file using Python’s csv module 563 A better way to read and write CSV files 566 Working with Excel files in Python 568 Binary file formats for data exports 569 Working with XLSX files using the XlsxWriter package 569 XLSX files 569 Exercise 13.03 – creating XLSX files in Python 572 Working with PDF files in Python 575 Converting web pages into PDFs 575 Exercise 13.04 – generating a PDF version of a web page in Python 575 Playing with graphs in Python 578 Integrating plotly with Django 583 Integrating visualizations with Django 583 Exercise 13.06 – visualizing a user’s reading history on the user’s profile page 583 Activity 13.01 – exporting the books read by a user as an XLSLX file 589 Summary 590 14 Testing Your Django Applications 591 Technical requirements 592 Importance of testing 592 Automation testing 592 Testing in Django 593 Implementing test cases 594 Unit testing in Django 594 Utilizing assertions 594 Exercise 14.01 – writing a simple unit test 596 Performing pre-test setup and cleanup after every test case run 598 Testing Django models 599 Exercise 14.02 – testing Django models 599 Testing Django views 603 Exercise 14.03 – writing unit tests for Django views 604 Testing views with authentication 607 Exercise 14.04 – writing test cases to validate authenticated users 608 Django RequestFactory 612 Exercise 14.05 – using RequestFactory to test views 612 Testing class-based views 615 Test case classes in Django 615 The SimpleTestCase class 616 The TransactionTestCase class 616 The LiveServerTestCase class 616 Modularizing test code 617 Activity 14.01 – testing models and views in Bookr 618 Summary 619 15 Django Third-Party Libraries 621 Technical requirements 622 Environment variables 622 django-configurations 625 manage.py changes 627 Configuration from environment variables 628 Exercise 15.01 – Django configurations setup 629 dj-database-url 633 Exercise 15.02 – dj-database-url and setup 637 The Django Debug Toolbar 638 Exercise 15.03 – setting up the Django Debug Toolbar 655 django-crispy-forms 658 The crispy filter 659 The crispy template Tag 660 Exercise 15.04 – using Django Crispy Forms with SearchForm 662 django-allauth 667 django-allauth installation and setup 670 Initiating authentication with django-allauth 673 Other django-allauth features 673 Activity 15.01 – using FormHelper to update forms 674 Summary 677 16 Using a Frontend JavaScript Library with Django 679 Technical requirements 679 JavaScript frameworks 680 An introduction to JavaScript 682 Loading JavaScript 682 Variables and constants 683 Working with React 688 Components 689 Exercise 16.01 – setting up a React example 694 JSX – a JavaScript syntax extension 697 Exercise 16.02 – JSX and Babel 699 JSX properties 700 Exercise 16.03 – React component properties 701 JavaScript promises 703 The fetch function 704 Exercise 16.04 – fetching and rendering books 708 The verbatim template tag 712 Activity 16.01 – reviews preview 713 Summary 719 Index 721 Other Books You May Enjoy 736
Shaw Ben and others / Шоу Бен и другие - Web Development with Django: A definitive guide to building modern Python web applications using Django 4, 2nd Edition / Веб-разработка с помощью Django [2023, PDF, EPUB, ENG] download torrent for free and without registration
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