Please follow these coding standards when writing code for inclusion in Django. - Django Documentation
- Use EditorConfig or conform to the indentation style dictated in the .editorconfig file
- Use 4 spaces for indentation with Python and 2 indentation spaces for HTML files.
- Use PEP 8 Python style as a guide
- Use flake8 to check for problems in this area. But Django has line lengths rules that are different then PEP 8 recommends.
- Use four space hanging indentation rather than vertical alignment:
# Not like this way:
raise AttributeError('Here is a multiline error message '
'shortened for clarity.')
# Try it this way
raise AttributeError(
'Here is a multiline error message '
'shortened for clarity.'
)
- Use single quotes for strings, or a double quote if the string contains a single quote.
- Use underscores, not camelCase, for variable, function and method names
- Use InitialCaps for class names (or for factory functions that return classes)
- Use in tests, assertRaiseMessage() and assertWarnsMessage() instead of assertRaises() and assertWarns() to check for the exception or warning message
- Use isort to automate import sorting into these groups:
future, standard library, third-party libraries, other Django components, local Django component, try/excepts.
$ python -m pip install isort
installed info will be displayed here
$ isort -rc .
- This runs isort recursively from your current directory, modifying any files that don't conform to the guidelines. If you need your imports out of order to avoid a circular import use a comment like this:
import module # isort:skip
example django/contrib/admin/example.py
# future
from __future__ import unicode_literals
#standard library
import json
from itertools import chain
# third-party
import bcrypt
# Django
from django.http import Http404
from django.http.response import (
Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse, cookie,
)
# local Django
from .models import LogEntry
# try/except
try:
import yaml
except ImportError:
yaml = None
CONSTANT = 'foo'
class Example:
# ...
- Use convenience imports whenever available
# Instead of this:
from django.views.generic.base import View
# Do this:
from django.views import View
- When using Django template code, put one space between the curly brackets and the tag contents.
# Not like this:
{{foo}}
# Do this:
{{ foo }}
- Using Django views, the first parameter in a view function should be called request.
# This is not right:
def my_view(req, foo):
# ...
# Now this is better:
def my_view(request, foo):
# ...
- Field names should be all lowercase, using underscores instead of camelCase.
# This does not look good:
class Person(models.Model):
FirstName = models.CharField(max_length=20)
Last_Name = models.CharField(max_length=40)
# Looks way better:
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)
-
class Meta should appear after the fields are defined. Put a single blank line to separate the fields and the class definition. The order of the model inner classes and standard methods should be:
-
All database fields
-
Custom manager attributes
-
class Meta
-
def str()
-
def save()
-
def get_absolute_url()
-
Any custom methods
# Not like this example:
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)
class Meta:
verbose_name_plural = 'people'
# This is not the right way either
class Person(models.Model):
class Meta:
verbose_name_plural = 'people'
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)
# This is the way to do it:
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)
class Meta:
verbose_name_plural = 'people'
- If using choices for a given model field, define each choice as a list of tuples, with an all-uppercase name as a class attribute on the model.
# Example with model field that has choices defined in it.
class MyModel(models.Model):
DIRECTION_UP ='U'
DIRECTION_DOWN = 'D'
DIRECTION_CHOICES = [
(DIRECTION_UP, 'Up'),
(DIRECTION_DOWN, 'Down'),
]
- Avoid abbreviating variable names.
- Write out your function argument names. As we addressed above.
- Document your classes and methods. Your work now will pay in the future.
- Comment your code. This is good but it is more important to document your classes and methods.
- Refactor repeated lines of code into reusable functions or methods.
- Try to keep your functions and methods short.
- Use flake8 to check your code quality as we talked about at the beginning of this list.
- Use explicit relative imports to avoid program bloat.
- Avoid using import *
- Use underscores in URL pattern names instead of dashes.