Giter Club home page Giter Club logo

django-5-by-example's Introduction

Django 5 by Example

GitHub stars

This is the code repository for Django 5 by Example, written by Antonio Melé and published by Packt. It contains all the supporting project files necessary to work through the book from start to finish.

Technical Reviewer: Mark Walker
Foreword: Paolo Melchiorre

Instructions

The code is organised into directories with the chapter number. For example, Chapter02 contains the source code for chapter 2. Each chapter folder has a requirements.txt file that includes all packages required to run the code of that chapter. These can be installed with the command pip install -r requirements.txt.

Run the Django development server with the command:

python manage.py runserver

Docker Compose is explained in Chapter 17. However all chapters include a Docker Compose configuration and a management script (contribution by @marksweb).

Commands to build and run using Docker Compose:

./do.sh build
./do.sh run

List of commands:

  • build [<arg>]: Builds Docker images. Optional arguments can specify specific images to build.
  • exec [<arg>]: Execute a command in a container.
  • compose: Minimal wrapper around Docker Compose, ensuring correct configuration files are loaded.
  • migrate [<arg>]: Apply any unapplied Django migrations.
  • makemigrations [<arg>]: Create a new Django migration, specifying additional arguments if needed.
  • check: Validate Django settings.
  • shell: Open a bash terminal in the specified container (web_run).
  • start [<arg>]: Start the Django server and dependent services. Use -d to run detached.
  • stop [<arg>]: Stop the Django server and dependent services.

About the Book

Django 5 by Example (5th edition) will guide you through the entire process of developing professional web applications with Django. The book not only covers the most relevant aspects of the framework, but it will also teach you how to integrate other popular technologies into your Django projects.

The book will walk you through the creation of four real-world applications, solving common problems, and implementing best practices, using a step-by-step approach that is easy to follow.

After reading this book, you will have a good understanding of how Django works and how to build practical, advanced web applications.

Requirements

This book requires Python 3.12+ and Django 5.

Django Projects

The book covers a wide range of web app development topics divided into four different Django projects:

  • Blog Application (chapters 1-3): Create a complete blog application

    • Build data models, views, and URLs
    • Implement an administration site for your blog
    • Use canonical URLs for modles and implement SEO-friendly URLs for posts
    • Build post pagination and learn how to create class-based views
    • Use forms to allow readers to share posts via email and implement a comment system using model forms
    • Add tags to posts using django-taggit and recommend similar posts based on shared tags
    • Implement custom template tags to display latest posts and most commented posts
    • Implement a custom template filter to render Markdown
    • Create a sitemap and a RSS feed for your blog
    • Implement a full-text search engine using PostgreSQL
  • Social Website (chapters 4-7): Create a website to bookmark and share images

    • Implement authentication using the Django authentication framework
    • Extend the user model with a custom profile model
    • Use the Diango messages framework
    • Build a custom authentication backend
    • Implement social authentication (OAuth2) with Google using Python Social Auth
    • Use django-extensions to run the development server through HTTPS
    • Generate image thumbnails with easy-thumbnails
    • Implement many-to-many relationships in models
    • Build a JavaScript bookmarklet with JavaScript and Django
    • Add asynchronous HTTP requests with the JavaScript Fetch API and Django
    • Implement infinite scroll pagination
    • Build a user follow system
    • Create a user activity stream and optimize QuerySets
    • Learn to use Django signals
    • Use django-debug-toolbar to obtain relevant debug information
    • Count image views with Redis
    • Build an image ranking with Redis
  • Ecommerce Application (chapters 8-11): Create a fully-featured on-line shop

    • Build the models of the product catalog
    • Create a shopping cart using Django sessions
    • Create custom context processors
    • Manage customer orders
    • Send asynchronous notifications using Celery and RabbitMQ
    • Monitory Celery using Flower
    • Integrate Stripe to process payments
    • Implement a webhook to receive payment notifications from Stripe
    • Build custom views in the Django administration site
    • Create admin actions and generate CSV files
    • Generate PDF invoices dynamically using Weasyprint
    • Create a coupon system to apply disconts to orders
    • Integrate discounts with Stripe payments
    • Build a product recommendation engine using Redis
    • Add internationalization to the shop
    • Generate and manage translation files
    • Use Rosetta to manage translations
    • Translate URL patterns and build a language selector
    • Translate models using django-parler
    • Localize forms using django-localflavor
  • eLearning Platform (chapters 12-17): Create an eLearning platform including a CMS

    • Build course models
    • Create and use data fixtures
    • Use model inheritance to create polymorphic Content
    • Create a custom model field to order course contents
    • Implement authentication views
    • Build a content management system using class-based views and mixins
    • Restrict access using groups and permissions
    • Build formsets to manage course contents
    • Create drag-and-drop functionality to reorder content in-place using JavaScript and Django
    • Using generic mixins from django-braces
    • Implement public views and student enrolment views
    • Render different type of contents and use django-embed-video
    • Cache content using the cache framework
    • Use the Memached and Redis cache backends
    • Monitor Redis using django-redisboard
    • Build an API using Django REST Framework
    • Create serializers for models and custom API views
    • Handle API authentication and permissions
    • Build API viewsets and routers
    • Consume your API using Python requests
    • Create a real-time chat server using Django Channels
    • Implement a WebSocket consumer/client using Django and JavaScript
    • Use Redis to set up a channel layer
    • Make your WebSocket fully-asynchronous
    • Implement a chat history by persisting chat messages
    • Create settings for multiple environments
    • Configure a production environment using Docker Compose with PostgreSQL, Redis, Nginx, uWSGI and Daphne
    • Serve your project securely through HTTPS
    • Use the Django system check framework
    • Build a custom middleware
    • Create custom management commands

Community & Support

Join the book Discord Community to participate in the ongoing discussions or/and initiate a new one. You will find other developers reading the book alongside and helping each other with questions.

Source Code for Previous Editions

Editions in Other Languages

While the 5th edition of the book is translated to other languages, you can find translations for the previous editions:

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost. Simply click on the link to claim your free PDF: https://packt.link/free-ebook/9781805125457

Graphic Bundle

We also provide a PDF file that has color images of the screenshots/diagrams used in this book at GraphicBundle Coding

Errata

  • Page 39 Post.objects.filter(id_lt=3).count() code example should read Post.objects.filter(id__lt=3).count()

django-5-by-example's People

Contributors

anikets-cpu avatar kushal499 avatar packtriannar avatar zenx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-5-by-example's Issues

Typo on page 713 in chapter 16

Here is the screenshot from the book:
image

In raw_id_fields =[ 'user', 'content'] the content should be course as the value(s) of raw_id_fields must be either a foreign key or many-to-many field.

Here is the traceback (with docker-compose.yml)

web_1    | ERRORS:
web_1    | <class 'chat.admin.MessageAdmin'>: (admin.E003) The value of 'raw_id_fields[1]' must be a foreign key or a many-to-many field.

Bookmarklet.js is not working on some websites because "Content Security Policy of your site blocks some resources. Some resources are blocked because their origin is not listed in your site's Content Security Policy (CSP)."

Issue

I am following the social media project and everything is working right so far. The bookmarker is working on most websites, getting the images of the page. However, in popular websites, such as pinterest, youtube, and chatgpt.com, the script is getting blocked due to security/policy reasons.

Logs

In the console, the issue is this:

Some resources are blocked because their origin is not listed in your site's Content Security Policy (CSP). Your site's CSP is allowlist-based, so resources must be listed in the allowlist in order to be accessed.

A site's Content Security Policy is set either via an HTTP header (recommended), or via a meta HTML tag. To fix this issue do one of the following:

  • (Recommended) If you're using an allowlist for 'script-src', consider switching from an allowlist CSP to a strict CSP, because strict CSPs are more robust against XSS . See how to set a strict CSP .
  • Or carefully check that all of the blocked resources are trustworthy; if they are, include their sources in the CSP of your site. ⚠️Never add a source you don't trust to your site's CSP. If you don't trust the source, consider hosting resources on your own site instead.

Here is the picture:
pinterest

How should we configure the scripts to ensure that the bookmarker works on all sites?

bookmarklet_launcher.js - TemplateDoesNotExist

In the dashboard.html file which is inside bookmarks/account/templates/account/dashboard.html has the below paragraph:

<p>Drag the following button to your bookmarks toolbar to bookmark images from other websites → <a href="javascript:{% include "bookmarklet_launcher.js" %}" class="button">Bookmark it</a></p>

But this bookmarklet_launcher.js file is inside another django app - bookmarks/images/templates/bookmarklet_launcher.js.

When I run my Django app, I get the below error:

TemplateDoesNotExist
django.template.exceptions.TemplateDoesNotExist: bookmarklet_launcher.js

And I understand why this is happening. As how can I refer to a template that is not even in the same application. Plus, this is a .js file and not an html template, yet we have done a include template tag.

I am confused and have no idea, how to move forward.

Chapter 6. Issue in Bookmarking

As I click on Bookmark it this error shows up
image

image

and then it is not working as intended and i don't know what to do.

This is the bookmarklet.js code:

const siteUrl = "//127.0.0.1:8000/";
const styleUrl = siteUrl + "static/css/bookmarklet.css";
const minWidth = 250;
const minHeight = 250;

// load CSS
var head = document.getElementsByTagName("head")[0]; // Get HTML head element
var link = document.createElement("link"); // Create new link Element
link.rel = "stylesheet"; // set the attributes for link element
link.type = "text/css";
link.href = styleUrl + "?r=" + Math.floor(Math.random() * 9999999999999999);
head.appendChild(link); // Append link element to HTML head

// load HTML
var body = document.getElementsByTagName("body")[0];
const boxHtml = `
  <div id="bookmarklet">
    <a href="#" id="close">&times;</a>
    <h1>Select an image to bookmark:</h1>
    <div class="images"></div>
  </div>`;
body.innerHTML += boxHtml;

function bookmarkletLaunch() {
    const bookmarklet = document.getElementById("bookmarklet");
    var imagesFound = bookmarklet.querySelector(".images");

    // clear images found
    imagesFound.innerHTML = "";
    // display bookmarklet
    bookmarklet.style.display = "block";

    // close event
    bookmarklet.querySelector("#close").addEventListener("click", function () {
        bookmarklet.style.display = "none";
    });

    // find images in the DOM with the minimum dimensions
    var images = document.querySelectorAll(
        'img[src$=".jpg"], img[src$=".jpeg"], img[src$=".png"]'
    );
    images.forEach((image) => {
        if (
            image.naturalWidth >= minWidth &&
            image.naturalHeight >= minHeight
        ) {
            var imageFound = document.createElement("img");
            imageFound.src = image.src;
            imagesFound.append(imageFound);
        }
    });

    // select image event
    imagesFound.querySelectorAll("img").forEach((image) => {
        image.addEventListener("click", function (event) {
            const imageSelected = event.target;
            bookmarklet.style.display = "none";
            window.open(
                siteUrl +
                    "images/create/?url=" +
                    encodeURIComponent(imageSelected.src) +
                    "&title=" +
                    encodeURIComponent(document.title),
                "_blank"
            );
        });
    });
}
// launch the bookmarklet
bookmarkletLaunch();

Please help.

Chapter 6 -- "User" is not defined

Chapter 6 adds validation to ensure that email addresses are not reused when a user is registering or editing their profile.

However, the User object at

if User.objects.filter(email=data).exists():
and is not actually defined anywhere.

Comparing to https://github.com/PacktPublishing/Django-4-by-example/blob/main/Chapter05/bookmarks/account/forms.py, it looks like the import of User was replaced with get_user_model without fixing these two instances.

Doing something like the following solves the issue:

def clean_email(self):
        data = self.cleaned_data["email"]
        user = get_user_model()
        if user.objects.filter(email=data).exists():
            raise forms.ValidationError("Email already in use.")
        return data

...

def clean_email(self):
        data = self.cleaned_data["email"]
        user = get_user_model()
        qs = user.objects.exclude(id=self.instance.id).filter(email=data)
        if qs.exists():
            raise forms.ValidationError("Email already in use.")
        return data

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.