Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Code Formatting - Django Best Practices

Introduction

Code formatting is a crucial aspect of software development. It ensures that code is readable, maintainable, and consistent across different parts of a project. This tutorial will guide you through the best practices for formatting code in Django projects.

Indentation

Proper indentation is essential for readability. In Python, it is also syntactically significant. Use 4 spaces per indentation level.

Example:

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = MyForm()
    return render(request, 'my_template.html', {'form': form})

Line Length

Keep lines under 79 characters. This helps in maintaining readability and ensures that code fits well on screens and printouts.

Example:

# Good
def some_function():
    return HttpResponse("This is a response with a short line")

# Bad
def some_function():
    return HttpResponse("This is a response with a line that is way too long and exceeds the 79 character limit")

Blank Lines

Use blank lines to separate functions and classes, and larger blocks of code inside functions.

Example:

class MyModel(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


def my_view(request):
    return HttpResponse("Hello, world!")

Imports

Imports should be on separate lines and grouped in the following order:

  • Standard library imports
  • Related third-party imports
  • Local application/library specific imports

Example:

# Standard library imports
import os
import sys

# Third-party imports
import django
from django.conf import settings

# Local application imports
from myapp.models import MyModel

String Quotes

In Django projects, prefer using single quotes for strings unless the string contains a single quote, in which case, use double quotes.

Example:

# Good
name = 'John'

# Good
message = "John's book"

Comments

Use comments to explain why certain code exists. Do not use comments to explain what the code does; the code itself should be clear enough.

Example:

def calculate_discount(price, discount):
    # Ensure discount is a percentage
    if discount < 0 or discount > 100:
        raise ValueError("Discount must be between 0 and 100")
    return price - (price * discount / 100)

Function and Variable Names

Use descriptive names for functions and variables to make the code more readable. Follow the snake_case naming convention for functions and variables.

Example:

# Good
def calculate_total(price, tax):
    total = price + tax
    return total

# Bad
def calc(p, t):
    tot = p + t
    return tot

Class Names

Use CamelCase for class names. This helps distinguish classes from functions and variables.

Example:

class MyModel(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

Conclusion

Following these code formatting best practices will make your Django projects more readable, maintainable, and consistent. Adhering to a style guide not only improves the quality of your code but also makes collaboration with other developers easier.