O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Django Design Patterns and Best Practices - Second Edition

Book Description

Build maintainable websites with elegant Django design patterns and modern best practices

About This Book
  • Explore aspects of Django from Models and Views to testing and deployment
  • Understand the nuances of web development such as browser attack and data design
  • Walk through various asynchronous tools such as Celery and Channels
Who This Book Is For

This book is for you whether you're new to Django or just want to learn its best practices. You do not have to be an expert in Django or Python. No prior knowledge of patterns is expected for reading this book but it would be helpful.

What You Will Learn
  • Make use of common design patterns to help you write better code
  • Implement best practices and idioms in this rapidly evolving framework
  • Deal with legacy code and debugging
  • Use asynchronous tools such as Celery, Channels, and asyncio
  • Use patterns while designing API interfaces with the Django REST Framework
  • Reduce the maintenance burden with well-tested, cleaner code
  • Host, deploy, and secure your Django projects
In Detail

Building secure and maintainable web applications requires comprehensive knowledge. The second edition of this book not only sheds light on Django, but also encapsulates years of experience in the form of design patterns and best practices. Rather than sticking to GoF design patterns, the book looks at higher-level patterns. Using the latest version of Django and Python, you'll learn about Channels and asyncio while building a solid conceptual background. The book compares design choices to help you make everyday decisions faster in a rapidly changing environment.

You'll first learn about various architectural patterns, many of which are used to build Django. You'll start with building a fun superhero project by gathering the requirements, creating mockups, and setting up the project. Through project-guided examples, you'll explore the Model, View, templates, workflows, and code reusability techniques. In addition to this, you'll learn practical Python coding techniques in Django that'll enable you to tackle problems related to complex topics such as legacy coding, data modeling, and code reusability.

You'll discover API design principles and best practices, and understand the need for asynchronous workflows. During this journey, you'll study popular Python code testing techniques in Django, various web security threats and their countermeasures, and the monitoring and performance of your application.

Style and approach

This comprehensive project-driven guide will enhance your skill set by taking you through the well-known design patterns and industry-standard best practices in Django web development.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Django Design Patterns and Best Practices Second Edition
  3. PacktPub.com
    1. Why subscribe?
    2. PacktPub.com
  4. Contributors
    1. About the author
    2. About the reviewer
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Django and Patterns
    1. Why Django?
    2. The story of Django
      1. A framework is born
      2. Removing the magic
      3. Django keeps getting better
    3. How does Django work?
    4. What is a pattern?
      1. Gang of four patterns
      2. Is Django MVC?
      3. Fowler's patterns
      4. Are there more patterns?
    5. Patterns in this book
      1. Criticism of patterns
      2. How to use patterns
      3. Python Zen and Django's design philosophy
    6. Summary
  7. Application Design
    1. How to gather requirements?
    2. Are you a storyteller?
    3. HTML mockups
    4. Designing the application
      1. Dividing a project into apps
      2. Reuse or roll-your-own?
        1. My app sandbox
      3. Which packages made it?
    5. Best practices before starting a project
    6. SuperBook – your mission, should you choose to accept it
      1. Why Python 3?
      2. Which Django Version to use
      3. Starting the project
    7. Summary
  8. Models
    1. M is bigger than V and C
    2. The model hunt
      1. Splitting models.py into multiple files
    3. Structural patterns
      1. Patterns — normalized models
        1. Problem details
        2. Solution details
          1. Three steps of normalization
          2. First normal form (1NF)
          3. Second normal form (2NF)
          4. Third normal form (3NF)
          5. Django models
          6. Performance and denormalization
          7. Should we always normalize?
      2. Pattern — model mixins
        1. Problem details
        2. Solution details
          1. Model mixins
      3. Pattern — user profiles
        1. Problem details
        2. Solution details
          1. Signals
          2. Admin
          3. Multiple profile types
      4. Pattern – service objects
        1. Problem details
        2. Solution details
    4. Retrieval patterns
      1. Pattern — property field
        1. Problem details
        2. Solution details
          1. Cached properties
      2. Pattern — custom model managers
        1. Problem details
        2. Solution details
          1. Set operations on QuerySets
          2. Chaining multiple QuerySets
    5. Migrations
    6. Summary
  9. Views and URLs
    1. A view from the top
      1. Views got classier
    2. Class-based generic views
      1. Class-Based Views are not always Class-Based Generic Views
    3. View mixins
      1. Order of mixins
    4. Decorators
    5. View patterns
      1. Pattern — access controlled views
        1. Problem details
        2. Solution details
      2. Pattern — context enhancers
        1. Problem details
        2. Solution details
      3. Pattern – services
        1. Problem details
        2. Solution details
    6. Designing URLs
      1. URL anatomy
        1. What happens in urls.py?
        2. Simplified URL pattern syntax
        3. Regular expression URL pattern syntax
          1. Can the simplified syntax replace regular expressions?
        4. Names and namespaces
        5. Pattern order
        6. URL pattern styles
          1. Department store URLs
          2. RESTful URLs
    7. React.js, Vue.js, and other view replacements
    8. Summary
  10. Templates
    1. Understanding Django's template language features
      1. Variables
      2. Attributes
      3. Filters
      4. Tags
      5. Philosophy – don't invent a programming language
    2. Jinja2
    3. Organizing templates
    4. How templates work
    5. Using Bootstrap
      1. But they all look the same!
      2. Lightweight alternatives
    6. Template patterns
      1. Pattern — template inheritance tree
        1. Problem details
        2. Solution details
      2. Pattern — the active link
        1. Problem details
        2. Solution details
          1. A template-only solution
          2. Custom tags
    7. Summary
  11. Admin Interface
    1. Using the admin interface
    2. Enhancing models for the admin
      1. Not everyone should be an admin
    3. Admin interface customizations
      1. Changing the heading
      2. Changing the base and stylesheets
        1. Adding a rich-text editor for WYSIWYG editing
      3. Bootstrap-themed admin
      4. Complete overhauls
    4. Protecting the admin
      1. Pattern – feature flags
        1. Problem details
        2. Solution details
    5. Summary
  12. Forms
    1. How forms work
      1. Forms in Django
      2. Why does data need cleaning?
    2. Displaying forms
      1. Time to be crisp
    3. Understanding CSRF
    4. Form processing with class-based views
    5. Form patterns
      1. Pattern – dynamic form generation
        1. Problem details
        2. Solution details
      2. Pattern – user-based forms
        1. Problem details
        2. Solution details
      3. Pattern – multiple form actions per view
        1. Problem details
        2. Solution details
          1. Separate views for separate actions
          2. Same view for separate actions
      4. Pattern – CRUD views
        1. Problem details
        2. Solution details
    6. Summary
  13. Working Asynchronously
    1. Why asynchronous?
      1. Pitfalls of asynchronous code
    2. Asynchronous patterns
      1. Endpoint callback pattern
      2. Publish-subscribe pattern
      3. Polling pattern
    3. Asynchronous solutions for Django
      1. Working with Celery
        1. How Celery works
        2. Celery best practices
          1. Handling failure
          2. Idempotent tasks
          3. Avoid writing to shared or global state
          4. Database updates without race conditions
          5. Avoid passing complex objects to tasks
      2. Understanding asyncio
        1. asyncio versus threads
        2. The classic web-scraper example
          1. Synchronous web-scraping
          2. Asynchronous web-scraping
        3. Concurrency is not parallelism
      3. Entering Channels
        1. Listening to notifications with WebSockets
        2. Differences from Celery
    4. Summary
  14. Creating APIs
    1. RESTful API
      1. API design
        1. Versioning
    2. Django Rest framework
      1. Improving the Public Posts API
        1. Hiding the IDs
    3. API patterns
      1. Pattern – human browsable interface
        1. Problem details
        2. Solution details
      2. Pattern – Infinite Scrolling
        1. Problem details
        2. Solution details
    4. Summary
  15. Dealing with Legacy Code
    1. Finding the Django Version
      1. Activating the virtual environment
    2. Where are the files? This is not PHP
    3. Starting with urls.py
    4. Jumping around the code
    5. Understanding the code base
      1. Creating the big picture
      2. PyGraphviz installation and usage
    6. Incremental change or a full rewrite?
    7. Writing tests before making any changes
      1. Step-by-step process to writing tests
    8. Legacy database integration
    9. Future proofing
    10. Summary
  16. Testing and Debugging
    1. Why write tests?
    2. TDD
    3. Writing a test case
      1. The assert method
      2. Writing better test cases
    4. Mocking
    5. Pattern – Test fixtures and factories
      1. Problem details
      2. Solution details
    6. Learning more about testing
    7. Debugging
      1. Django debug page
        1. A better debug page
    8. The print function
    9. Logging
    10. The Django Debug Toolbar
    11. The Python debugger pdb
    12. Other debuggers
    13. Debugging Django templates
    14. Summary
  17. Security
    1. Cross-site scripting
      1. Why are your cookies valuable?
      2. How Django helps
      3. Where Django might not help
    2. Cross-site request forgery
      1. How Django helps
      2. Where Django might not help
    3. SQL injection
      1. How Django helps
      2. Where Django might not help
    4. Clickjacking
      1. How Django helps
    5. Shell injection
      1. How Django helps
      2. And the web attacks are unending
    6. A handy security checklist
    7. Summary
  18. Production-Ready
    1. The production environment
      1. Choosing a web stack
      2. Components of a stack
    2. Virtual machines or Docker
      1. Microservices
    3. Hosting
      1. Platform as a service
      2. Virtual private servers
      3. Serverless
      4. Other hosting approaches
    4. Deployment tools
      1. Fabric
        1. Typical deployment steps
      2. Configuration management
    5. Monitoring
    6. Improving Performance
      1. Frontend performance
      2. Backend performance
        1. Templates
        2. Database
        3. Caching
          1. Cached session backend
          2. Caching frameworks
          3. Caching patterns
    7. Summary
  19. Python 2 Versus Python 3
    1. Python 3
      1. Python 3 for Djangonauts
      2. Change all __unicode__ methods into __str__
      3. All classes inherit from object
      4. Calling super() is easier
      5. Relative imports must be explicit
      6. HttpRequest and HttpResponse have str and bytes types
      7. f-strings or formatted string literals
      8. Exception syntax changes and improvements
      9. Standard library reorganized
      10. New goodies
        1. Pyvenv and pip are built in
      11. Other changes
    2. Further information
  20. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think