Sitemap
Sagar Chopade

Sagar Chopade

Software Engineer at scalereal

Django Best Practices

5 min readFeb 2, 2023

--

Press enter or click to view image in full size

In this blog post, we’ll explore some of the key best practices for building robust and maintainable django projects.

Greetings and welcome to the Python and Django worlds! 😃 You are now embarking on a journey to learn one of the most popular and widely used programming languages and frameworks. With Python, you can build a wide range of applications, from simple scripts to complex web applications with Django. The possibilities are endless, and the learning experience will be both challenging and rewarding. Best wishes on your journey, and please do not hesitate to ask for assistance when you need it.

At ScaleReal we work extensively on Python/Django Applications and have built a lot of highly scalable applications for various clients of ours.

Why should we follow Django’s best practices? 🤔

Django’s best practices are important because it helps ensure that your code is maintainable, scalable, secure, and efficient. Adhering to these practices helps you to write clean and organized code that is easy to understand and modify, even for other developers. Additionally, best practices help you avoid common security vulnerabilities and performance bottlenecks. By following these guidelines, you can build robust and reliable applications that are well-suited for long-term use.🤗

▪ Use virtual environments

Using virtual environments helps keep dependencies isolated and helps prevent version conflicts.

▪ Read variables from the environment

Environment variables provide a good way to set application execution parameters that are used by processes so that you can control the execution flow of the application before starting the application.

▪ Use Cached Loading

To improve the performance of a website by storing frequently accessed data in memory, instead of fetching it from the database every time it’s requested. This reduces the load on the database server and speeds up the website, making it more responsive to users. Caching can be especially beneficial for dynamic websites that receive a large amount of traffic.

▪ Use class-based views

Class-based views in Django provide a way to define reusable, modular views for your application. They offer several benefits over the traditional function-based view, like Code Reusability, Good Readability, Better Structure, Flexibility, and the DRY (Don’t Repeat Yourself) Principle. 🫶

▪ Use a good Application Structure

It can further organize the structure of Django into smaller, reusable components to make your application more maintainable. It is important to follow best practices and keep the structure of your application organized and easy to understand. Also, you can revise based on your need.

Get Sagar Chopade’s stories in your inbox

Join Medium for free to get updates from this writer.

given snippets show the app structure 👇

sagar@scalereal:/project# tree project/apps/dashboards/  
project/apps/dashboards/
├── __init__.py
├── api
│ ├── __init__.py
│ ├── urls.py
│ ├── views.py
│ └── serializers.py
├── admin.py
├── apps.py
├── management
│ ├── __init__.py
│ └── commands
│ ├── __init__.py
│ └── seed_random_data.py
├── migrations
│ └── __init__.py
├── models.py
├── services
│ ├── __init__.py
│ ├── business_logic_1.py
| └── business_logic_n.py
├── static
│ └── dashboards
│ ├── css
│ ├── img
│ └── js
├── templates
│ └── dashboards
│ └── index.html
├── templatetags
│ ├── __init__.py
│ └── temp_1.py
├── tests
│ ├── test_urls.py
│ ├── test_models.py
│ ├── test_templates.py
│ └── test_views.py
├── urls.py
└── views.py

The below snippets will show the project structure👇

sagar@scalereal:/# tree -L 4
.
├── docs
├── logs
├── media
├── project
│ ├── apps
│ │ ├── apiv1
│ │ ├── audits
│ │ ├── authorizations
│ │ ├── dashboards
│ │ ├── notifications
│ │ └── users
│ ├── common
│ │ ├── __init__.py
│ │ ├── exceptions.py
│ │ ├── helpers.py
│ │ ├── models.py
│ │ ├── pagination.py
│ │ ├── utils.py
│ │ └── validators.py
│ ├── config
│ │ ├── asgi.py
│ │ ├── __init__.py
│ │ ├── settings
│ │ | ├── __init__.py
│ │ | └── django.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ └── staticfiles
│ ├── admin
│ ├── apiv1
│ ├── rest_framework
│ └── dashboards
├── decision_logs
│ └── v1_db_schema.png
├── Dockerfile
├── manage.py
├── Pipfile
├── Pipfile.lock
├── pytest.ini
└── README.md

▪ Use cache template loader

It catches the compiled version of a template in memory so that subsequent requests for the same template can be served more quickly. This can significantly improve the performance of your website, especially for high-traffic sites with many templates.

▪ Write Separate business logic from the views✨

separating business logic from views makes your Django application more organized, maintainable, and scalable

▪ Store the Sessions in the Cache

By default, django stores all user sessions in the databases. So developers have to execute one or many SQL queries in order to retrieve the user session data from its respective database and retrieve the required user object information for the user🔥. Also, developers must clean the old user sessions that are already stored in the database, and this cleaning must happen at regular intervals. But as a developer, you still have the option to store the session data temporarily in the form of a cache by enabling the Memcached option or with the help of tools like Redis💡. When the session data is stored in the cache, the SQL query can bypass the execution each time the application is created and made a request. However, developers still need to store the session data in its respective database in the long run.

▪ Robust and persistent Database Connections

In the django database connection remains open for a prolonged period of time, instead of being closed after each request🔥. This can improve the performance of a Django application by reducing the overhead of establishing a new database connection for each request. You can achieve this by using updating the value of the CONN_MAX_AGE variable using django database settings prams by default value is 0, which means that the connection will be closed after each request.

Note ✍️ : persistent database connections are not suitable for all types of applications, and may not be the best choice for high-traffic applications or for applications that require a high degree of data consistency. Before implementing persistent database connections, it’s recommended to thoroughly test the performance and behavior of your application to ensure that it meets your requirements.

Also, 💥Django 4.1 support the health checks before we reuse them in each request performing database access. If the health check fails, the connection will be re-established without failing the request when the connection is no longer usable, but the database server is ready to accept and serve new connections. You can achieve this by updating the value of CONN_HEALTH_CHECKS by default value is false🤯.

That’s it from my side folks 🧑‍💻. I hope this blog has been helpful in giving you a better understanding of the best practices of django. Until next time, stay safe and keep learning!

What’s next now? 👉Will take a deep dive into the world of django models key best practices with our next tech blog post. Get ready for some mind-blowing information.

At ScaleReal We believe in Sharing and Open Source.

Thanks for reading!🫡 If you enjoyed reading this article, please click the 👏 button and share it with everyone. Feel free to leave a comment 💬 below.

Sharing is Caring!

Thank You :) 🙏

If you need any help, you can contact me on LinkedIn, Github, or Twitter.

~Sagar Chopade

--

--