Django 4 By Example - Antonio Melé - E-Book

Django 4 By Example E-Book

Antonio Mele

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Django 4 By Example is the 4th edition of the best-selling franchise that helps you build web apps. This book will walk you through the creation of real-world applications, solving common problems, and implementing best practices using a step-by-step approach.

You'll cover a wide range of web app development topics as you build four different apps:

A blog application: Create data models, views, and URLs and implement an admin site for your blog. Create sitemaps and RSS feeds and implement a full-text search engine with PostgreSQL.

A social website: Implement authentication with Facebook, Twitter, and Google. Create user profiles, image thumbnails, a bookmarklet, and an activity stream. Implement a user follower system and add infinite scroll pagination to your website.

An e-commerce application: Build a product catalog, a shopping cart, and asynchronous tasks with Celery and RabbitMQ. Process payments with Stripe and manage payment notifications via webhooks. Build a product recommendation engine with Redis. Create PDF invoices and export orders to CSV.

An e-learning platform: Create a content management system to manage polymorphic content. Cache content with Memcached and Redis. Build and consume a RESTful API. Implement a real-time chat using WebSockets with ASGI. Create a production environment using NGINX, uWSGI and Daphne with Docker Compose.

This is a practical book that will have you creating web apps quickly.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 846

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Django 4 By Example

Fourth Edition

Build powerful and reliable Python web applications from scratch

Antonio Melé

BIRMINGHAM—MUMBAI

Django 4 By Example

Fourth Edition

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Manish Nainani

Acquisition Editor – Peer Reviews: Suresh Jain

Project Editor: Amisha Vathare

Content Development Editor: Bhavesh Amin

Copy Editor: Safis Editing

Technical Editor: Aditya Sawant

Proofreader: Safis Editing

Indexer: Sejal Dsilva

Presentation Designer: Pranit Padwal

First published: November 2015

Second edition: May 2018

Third edition: March 2020

Fourth edition: August 2022

Production reference: 3150223

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80181-305-1

www.packt.com

To my sister Paloma.

Foreword

Django: The web framework for perfectionists with deadlines.

I like this tagline because it can be easy for developers to fall prey to perfectionism when having to deliver workable code on time.

There are many great web frameworks out there, but sometimes they assume too much of the developer, for example, how to properly structure a project, find the right plugins and elegantly use existing abstractions.

Django takes most of that decision fatigue away and provides you with so much more. But it's also a big framework, so learning it from scratch can be overwhelming.

I learned Django in 2017, head-on, out of necessity, when we decided it would be our core technology for our Python coding platform (CodeChalleng.es). I forced myself to learn the ins and outs by building a major real-world solution that has served thousands of aspiring and experienced Python developers since its inception.

Somewhere in this journey, I picked up an early edition of this book. It turned out to be a treasure trove. Very close to our hearts at Pybites, it teaches you Django by building interesting, real-world applications. Not only that, Antonio brings a lot of real-world experience and knowledge to the table, which shows in how he implements those projects.

And Antonio never misses an opportunity to introduce lesser-known features, for example, optimizing database queries with Postgres, useful packages like django-taggit, social auth using various platforms, (model) managers, inclusion template tags, and much more.

In this new edition, he even added additional schemas, images, and notes in several chapters and moved from jQuery to vanilla JavaScript (nice!)

This book not only covers Django thoroughly, using clean code examples that are well explained, it also explains related technologies which are a must for any Django developer: Django REST Framework, django-debug-toolbar, frontend / JS, and, last but not least, Docker.

More importantly, you'll find many nuances that you'll encounter and best practices you'll need to be an effective Django developer in a professional setting.

Finding a multifaceted resource like this is hard, and I want to thank Antonio for all the hard work he consistently puts into keeping it up to date.

As a Python developer that uses Django a lot, Django by Example has become my GO TO guide, an unmissable resource I want to have close by my desk. Every time I come back to this book, I learn new things, even after having read it multiple times and having used Django for a solid five years now.

If you embark on this journey, be prepared to get your hands dirty. It's a practical guide, so brew yourself a good coffee and expect to sink your teeth into a lot of Django code! But that's how we best learn, right? :)

- Bob Belderbos

Co-Founder of Pybites

Contributors

About the author

Antonio Melé is the co-founder and chief technology officer of Nucoro, the fintech platform that allows financial institutions to build, automate, and scale digital wealth management products. Antonio is also CTO of Exo Investing, an AI-driven digital investment platform for the UK market.

Antonio has been developing Django projects since 2006 for clients across several industries. In 2009 Antonio founded Zenx IT, a development company specialized in building digital products. He has been working as a CTO and technology consultant for multiple technology-based startups and he has managed development teams building projects for large digital businesses. Antonio holds an MSc. in Computer Science from ICAI - Universidad Pontificia Comillas, where he mentors early-stage startups. His father inspired his passion for computers and programming.

About the reviewer

Asif Saif Uddin is a software craftsman from Bangladesh. He has a decade-long professional experience working with Python and Django. Besides working for different start-ups and clients, Asif also contributes to some frequently used Python and Django packages. For his open-source contributions, he is now a core maintainer of Celery, oAuthLib, PyJWT, and auditwheel. He is also co-maintainer of several Django and Django REST framework extension packages. He is a voting member of the Django Software Foundation (DSF) and a contributing/managing member of the Python Software Foundation (PSF). He has been mentoring many young people to learn Python and Django, both professionally and personally.

A special thanks to Karen Stingel and Ismir Kullolli for reading and providing feedback on the book to enhance the content further. Your help is much appreciated!

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Building a Blog Application

Installing Python

Creating a Python virtual environment

Installing Django

Installing Django with pip

New features in Django 4

Django overview

Main framework components

The Django architecture

Creating your first project

Applying initial database migrations

Running the development server

Project settings

Projects and applications

Creating an application

Creating the blog data models

Creating the Post model

Adding datetime fields

Defining a default sort order

Adding a database index

Activating the application

Adding a status field

Adding a many-to-one relationship

Creating and applying migrations

Creating an administration site for models

Creating a superuser

The Django administration site

Adding models to the administration site

Customizing how models are displayed

Working with QuerySets and managers

Creating objects

Updating objects

Retrieving objects

Using the filter() method

Using exclude()

Using order_by()

Deleting objects

When QuerySets are evaluated

Creating model managers

Building list and detail views

Creating list and detail views

Using the get_object_or_404 shortcut

Adding URL patterns for your views

Creating templates for your views

Creating a base template

Creating the post list template

Accessing our application

Creating the post detail template

The request/response cycle

Additional resources

Summary

Join us on Discord.

Enhancing Your Blog with Advanced Features

Using canonical URLs for models

Creating SEO-friendly URLs for posts

Modifying the URL patterns

Modifying the views

Modifying the canonical URL for posts

Adding pagination

Adding pagination to the post list view

Creating a pagination template

Handling pagination errors

Building class-based views

Why use class-based views

Using a class-based view to list posts

Recommending posts by email

Creating forms with Django

Handling forms in views

Sending emails with Django

Sending emails in views

Rendering forms in templates

Creating a comment system

Creating a model for comments

Adding comments to the administration site

Creating forms from models

Handling ModelForms in views

Creating templates for the comment form

Adding comments to the post detail view

Adding comments to the post detail template

Additional resources

Summary

Extending Your Blog Application

Adding the tagging functionality

Retrieving posts by similarity

Creating custom template tags and filters

Implementing custom template tags

Creating a simple template tag

Creating an inclusion template tag

Creating a template tag that returns a QuerySet

Implementing custom template filters

Creating a template filter to support Markdown syntax

Adding a sitemap to the site

Creating feeds for blog posts

Adding full-text search to the blog

Installing PostgreSQL

Creating a PostgreSQL database

Dumping the existing data

Switching the database in the project

Loading the data into the new database

Simple search lookups

Searching against multiple fields

Building a search view

Stemming and ranking results

Stemming and removing stop words in different languages

Weighting queries

Searching with trigram similarity

Additional resources

Summary

Building a Social Website

Creating a social website project

Starting the social website project

Using the Django authentication framework

Creating a login view

Using Django authentication views

Login and logout views

Change password views

Reset password views

User registration and user profiles

User registration

Extending the user model

Installing Pillow and serving media files

Creating migrations for the profile model

Using a custom user model

Using the messages framework

Building a custom authentication backend

Preventing users from using an existing email

Additional resources

Summary

Join us on Discord.

Implementing Social Authentication

Adding social authentication to your site

Running the development server through HTTPS

Authentication using Facebook

Authentication using Twitter

Authentication using Google

Creating a profile for users that register with social authentication

Additional resources

Summary

Sharing Content on Your Website

Creating an image bookmarking website

Building the image model

Creating many-to-many relationships

Registering the image model in the administration site

Posting content from other websites

Cleaning form fields

Installing the Requests library

Overriding the save() method of a ModelForm

Building a bookmarklet with JavaScript

Creating a detail view for images

Creating image thumbnails using easy-thumbnails

Adding asynchronous actions with JavaScript

Loading JavaScript on the DOM

Cross-site request forgery for HTTP requests in JavaScript

Performing HTTP requests with JavaScript

Adding infinite scroll pagination to the image list

Additional resources

Summary

Tracking User Actions

Building a follow system

Creating many-to-many relationships with an intermediary model

Creating list and detail views for user profiles

Adding user follow/unfollow actions with JavaScript

Building a generic activity stream application

Using the contenttypes framework

Adding generic relations to your models

Avoiding duplicate actions in the activity stream

Adding user actions to the activity stream

Displaying the activity stream

Optimizing QuerySets that involve related objects

Using select_related()

Using prefetch_related()

Creating templates for actions

Using signals for denormalizing counts

Working with signals

Application configuration classes

Using Django Debug Toolbar

Installing Django Debug Toolbar

Django Debug Toolbar panels

Django Debug Toolbar commands

Counting image views with Redis

Installing Docker

Installing Redis

Using Redis with Python

Storing image views in Redis

Storing a ranking in Redis

Next steps with Redis

Additional resources

Summary

Building an Online Shop

Creating an online shop project

Creating product catalog models

Registering catalog models on the administration site

Building catalog views

Creating catalog templates

Building a shopping cart

Using Django sessions

Session settings

Session expiration

Storing shopping carts in sessions

Creating shopping cart views

Adding items to the cart

Building a template to display the cart

Adding products to the cart

Updating product quantities in the cart

Creating a context processor for the current cart

Context processors

Setting the cart into the request context

Registering customer orders

Creating order models

Including order models in the administration site

Creating customer orders

Asynchronous tasks

Working with asynchronous tasks

Workers, message queues, and message brokers

Using Django with Celery and RabbitMQ

Monitoring Celery with Flower

Additional resources

Summary

Join us on Discord.

Managing Payments and Orders

Integrating a payment gateway

Creating a Stripe account

Installing the Stripe Python library

Adding Stripe to your project

Building the payment process

Integrating Stripe Checkout

Testing the checkout process

Using test credit cards

Checking the payment information in the Stripe dashboard

Using webhooks to receive payment notifications

Creating a webhook endpoint

Testing webhook notifications

Referencing Stripe payments in orders

Going live

Exporting orders to CSV files

Adding custom actions to the administration site

Extending the administration site with custom views

Generating PDF invoices dynamically

Installing WeasyPrint

Creating a PDF template

Rendering PDF files

Sending PDF files by email

Additional resources

Summary

Extending Your Shop

Creating a coupon system

Building the coupon model

Applying a coupon to the shopping cart

Applying coupons to orders

Creating coupons for Stripe Checkout

Adding coupons to orders on the administration site and to PDF invoices

Building a recommendation engine

Recommending products based on previous purchases

Additional resources

Summary

Adding Internationalization to Your Shop

Internationalization with Django

Internationalization and localization settings

Internationalization management commands

Installing the gettext toolkit

How to add translations to a Django project

How Django determines the current language

Preparing your project for internationalization

Translating Python code

Standard translations

Lazy translations

Translations including variables

Plural forms in translations

Translating your own code

Translating templates

The {% trans %} template tag

The {% blocktrans %} template tag

Translating the shop templates

Using the Rosetta translation interface

Fuzzy translations

URL patterns for internationalization

Adding a language prefix to URL patterns

Translating URL patterns

Allowing users to switch language

Translating models with django-parler

Installing django-parler

Translating model fields

Integrating translations into the administration site

Creating migrations for model translations

Using translations with the ORM

Adapting views for translations

Format localization

Using django-localflavor to validate form fields

Additional resources

Summary

Building an E-Learning Platform

Setting up the e-learning project

Serving media files

Building the course models

Registering the models in the administration site

Using fixtures to provide initial data for models

Creating models for polymorphic content

Using model inheritance

Abstract models

Multi-table model inheritance

Proxy models

Creating the Content models

Creating custom model fields

Adding ordering to module and content objects

Adding authentication views

Adding an authentication system

Creating the authentication templates

Additional resources

Summary

Join us on Discord.

Creating a Content Management System

Creating a CMS

Creating class-based views

Using mixins for class-based views

Working with groups and permissions

Restricting access to class-based views

Managing course modules and their contents

Using formsets for course modules

Adding content to course modules

Managing modules and their contents

Reordering modules and their contents

Using mixins from django-braces

Additional resources

Summary

Rendering and Caching Content

Displaying courses

Adding student registration

Creating a student registration view

Enrolling on courses

Accessing the course contents

Rendering different types of content

Using the cache framework

Available cache backends

Installing Memcached

Installing the Memcached Docker image

Installing the Memcached Python binding

Django cache settings

Adding Memcached to your project

Cache levels

Using the low-level cache API

Checking cache requests with Django Debug Toolbar

Caching based on dynamic data

Caching template fragments

Caching views

Using the per-site cache

Using the Redis cache backend

Monitoring Redis with Django Redisboard

Additional resources

Summary

Building an API

Building a RESTful API

Installing Django REST framework

Defining serializers

Understanding parsers and renderers

Building list and detail views

Consuming the API

Creating nested serializers

Building custom API views

Handling authentication

Adding permissions to views

Creating ViewSets and routers

Adding additional actions to ViewSets

Creating custom permissions

Serializing course contents

Consuming the RESTful API

Additional resources

Summary

Building a Chat Server

Creating a chat application

Implementing the chat room view

Real-time Django with Channels

Asynchronous applications using ASGI

The request/response cycle using Channels

Installing Channels

Writing a consumer

Routing

Implementing the WebSocket client

Enabling a channel layer

Channels and groups

Setting up a channel layer with Redis

Updating the consumer to broadcast messages

Adding context to the messages

Modifying the consumer to be fully asynchronous

Integrating the chat application with existing views

Additional resources

Summary

Going Live

Creating a production environment

Managing settings for multiple environments

Local environment settings

Running the local environment

Production environment settings

Using Docker Compose

Installing Docker Compose

Creating a Dockerfile

Adding the Python requirements

Creating a Docker Compose file

Configuring the PostgreSQL service

Applying database migrations and creating a superuser

Configuring the Redis service

Serving Django through WSGI and NGINX

Using uWSGI

Configuring uWSGI

Using NGINX

Configuring NGINX

Using a hostname

Serving static and media assets

Collecting static files

Serving static files with NGINX

Securing your site with SSL/TLS

Checking your project for production

Configuring your Django project for SSL/TLS

Creating an SSL/TLS certificate

Configuring NGINX to use SSL/TLS

Redirecting HTTP traffic over to HTTPS

Using Daphne for Django Channels

Using secure connections for WebSockets

Including Daphne in the NGINX configuration

Creating a custom middleware

Creating a subdomain middleware

Serving multiple subdomains with NGINX

Implementing custom management commands

Additional resources

Summary

Other Books You May Enjoy

Index

Landmarks

Cover

Index

Share your thoughts

Once you’ve read Django 4 By Example, Fourth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781801813051

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly