Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Django in Production

You're reading from  Django in Production

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781804610480
Pages 348 pages
Edition 1st Edition
Languages
Author (1):
Arghya Saha Arghya Saha
Profile icon Arghya Saha

Table of Contents (21) Chapters

Preface 1. Part 1 – Using Django and DRF to Build Modern Web Application
2. Chapter 1: Setting Up Django with DRF 3. Chapter 2: Exploring Django ORM, Models, and Migrations 4. Chapter 3: Serializing Data with DRF 5. Chapter 4: Exploring Django Admin and Management Commands 6. Chapter 5: Mastering Django Authentication and Authorization 7. Part 2 – Using the Advanced Concepts of Django
8. Chapter 6: Caching, Logging, and Throttling 9. Chapter 7: Using Pagination, Django Signals, and Custom Middleware 10. Chapter 8: Using Celery with Django 11. Chapter 9: Writing Tests in Django 12. Chapter 10: Exploring Conventions in Django 13. Part 3 – Dockerizing and Setting Up a CI Pipeline for Django Application
14. Chapter 11: Dockerizing Django Applications 15. Chapter 12: Working with Git and CI Pipelines Using Django 16. Part 4 – Deploying and Monitoring Django Applications in Production
17. Chapter 13: Deploying Django in AWS 18. Chapter 14: Monitoring Django Application 19. Index 20. Other Books You May Enjoy

Exploring Conventions in Django

In previous chapters, we learned about the different features of Django and how you can utilize these features to build a scalable Django application. Django is considered to be opinionated; it doesn’t give a lot of flexibility to developers. Being opinionated has led to a love-hate relationship between Django and the developer community, where a lot of developers love the fact that Django has a particular way of performing certain implementations and developers do not have to think too much about how to use Django to build a web service. However, many developers don’t like Django due to the lack of flexibility and its being too rigid about how a particular code should be written.

In this chapter, we will learn about certain conventions you can follow while working with Django. You should note that this chapter contains a lot of opinionated concepts that I have learned while working on numerous Django projects and consulting for different...

Technical requirements

We will learn the conventions of different Django topics we have covered so far in this book. You should be well versed in all the topics explained in earlier chapters.

Here is the GitHub repository that has all the code and instructions for this chapter: https://github.com/PacktPublishing/Django-in-Production/tree/main/Chapter10.

Code structuring for Django projects

When we start a new project in Django, the Django management command creates the basic files needed to create our Django project. In Chapter 1, we learned how we can set up our Django project and create different Django apps. In this section, we shall collate all the information we have gathered in previous chapters on using different files for different purposes in Django.

Creating files as per functionalities

As a first step in bifurcation, we have already learned that we should create multiple Django apps in our Django project. The splitting of a Django app depends on the business logic functionalities; for example, our blogging project can have blog and author as two different Django apps. Inside each app, we would split our code into multiple files. Here is the recommended list of files we should consider while working on Django:

  • urls.py: Each Django application should have a urls.py file that contains all the routing logic for...

Working with exceptions and errors

Developers should always think through all the corner cases possible and write code to handle all those corner cases. Unfortunately, bugs, exceptions, and errors can still slip into production, leading to our users having a bad experience. We have already learned, in Chapter 9, how test cases can help us catch these errors better in the development phase itself, and to improve the user experience, we should show appropriate error messages whenever something breaks. For example, if the server is expecting name to be present in the body of the request and it is missing, then we should send an error message explicitly saying name field is missing.

Here are a few important points we should follow while handling exceptions and errors:

  • Always send the appropriate status code. If the request body is missing certain information, then pass 400 and then pass a message explaining the missing information.
  • If the error is an authentication error...

Using feature flags

A feature flag is a technique to enable or disable certain functionalities in code during runtime without deploying new code. This helps developers to toggle different features in production at a much faster rate. For example, if a company has incorporated Stripe and PayPal payment gateways for payments in their app, but for some reason Stripe is down, then the team can quickly change their payment gateway to PayPal without any code change or deployment. This is very common for critical systems and also while building new systems.

In the following example code, we are storing the payment gateway configuration in our KeyValueStore database table. This helps us to control the payment gateway at runtime. KeyValueStore is a database model that is stored in the common/models.py file:

class KeyValueStore(models.Model):
    key = models.CharField(max_length=255, unique=True)
    value = models.JSONField()
   ...

Configuring Django for production

In this section, we will learn about a few key configurations we need to set before deploying to production. We will first discuss the configuration we need to update the settings.py file:

  • Update the SECRET_KEY value and pass it via the environment variable
  • Set DEBUG = False for production so that sensitive information via an error stacktrace is not shown, whenever there is an error in the Django app
  • Set ALLOWED_HOSTS = ["dip.com", "xyz.com"], and list all the domains that the Django project would be served on
  • Set APPEND_SLASH = True so that if any request is missing a slash at the end, Django can add a slash automatically
  • Set TIME_ZONE appropriately

There are a few more configurations that you can update in the Django settings. They depend on the Django project use case. Apart from the preceding mentioned settings, let’s learn about a couple of other configurations we need to perform:

    ...

Summary

In this chapter, we learned about different conventions we can implement in our Django project. We learned how we can create different files in our Django project and structure them properly to write scalable and maintainable code, as well as avoiding circular dependency errors as our project expands. Exception and error handling is an important concept that we have learned about in this chapter. We understood how error codes can help us debug properly in production.

We saw how feature flags can help us to have better control over our code and enable/disable certain functionalities during runtime without requiring any additional deployment of code to our servers. Then, we saw some tips and tricks to configure our Django application before deploying it to production. CORS and WSGI are critical specifications for web development, and we learned about them, as well as the django-cors-headers and gunicorn packages, in this chapter. We also learned about application development...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Django in Production
Published in: Apr 2024 Publisher: Packt ISBN-13: 9781804610480
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}