Coding style

Please follow these coding standards when writing code for inclusion in Django.

Pre-commit checks

pre-commit is a framework for managing pre-commit hooks. These hooks help to identify simple issues before committing code for review. By checking for these issues before code review it allows the reviewer to focus on the change itself, and it can also help to reduce the number of CI runs.

To use the tool, first install pre-commit and then the git hooks:

/ 

  1. $ python -m pip install pre-commit
  2. $ pre-commit install
  1. ...\> py -m pip install pre-commit
  2. ...\> pre-commit install

On the first commit pre-commit will install the hooks, these are installed in their own environments and will take a short while to install on the first run. Subsequent checks will be significantly faster. If an error is found an appropriate error message will be displayed. If the error was with black or isort then the tool will go ahead and fix them for you. Review the changes and re-stage for commit if you are happy with them.

Python style

  • All files should be formatted using the black auto-formatter. This will be run by pre-commit if that is configured.

  • The project repository includes an .editorconfig file. We recommend using a text editor with EditorConfig support to avoid indentation and whitespace issues. The Python files use 4 spaces for indentation and the HTML files use 2 spaces.

  • Unless otherwise specified, follow PEP 8.

    Use flake8 to check for problems in this area. Note that our setup.cfg file contains some excluded files (deprecated modules we don’t care about cleaning up and some third-party code that Django vendors) as well as some excluded errors that we don’t consider as gross violations. Remember that PEP 8 is only a guide, so respect the style of the surrounding code as a primary goal.

    An exception to PEP 8 is our rules on line lengths. Don’t limit lines of code to 79 characters if it means the code looks significantly uglier or is harder to read. We allow up to 88 characters as this is the line length used by black. This check is included when you run flake8. Documentation, comments, and docstrings should be wrapped at 79 characters, even though PEP 8 suggests 72.

  • String variable interpolation may use %-formatting, f-strings, or str.format() as appropriate, with the goal of maximizing code readability.

    Final judgments of readability are left to the Merger’s discretion. As a guide, f-strings should use only plain variable and property access, with prior local variable assignment for more complex cases:

    1. # Allowed
    2. f"hello {user}"
    3. f"hello {user.name}"
    4. f"hello {self.user.name}"
    5. # Disallowed
    6. f"hello {get_user()}"
    7. f"you are {user.age * 365.25} days old"
    8. # Allowed with local variable assignment
    9. user = get_user()
    10. f"hello {user}"
    11. user_days_old = user.age * 365.25
    12. f"you are {user_days_old} days old"

    f-strings should not be used for any string that may require translation, including error and logging messages. In general format() is more verbose, so the other formatting methods are preferred.

    Don’t waste time doing unrelated refactoring of existing code to adjust the formatting method.

  • Avoid use of “we” in comments, e.g. “Loop over” rather than “We loop over”.

  • Use underscores, not camelCase, for variable, function and method names (i.e. poll.get_unique_voters(), not poll.getUniqueVoters()).

  • Use InitialCaps for class names (or for factory functions that return classes).

  • In docstrings, follow the style of existing docstrings and PEP 257.

  • In tests, use assertRaisesMessage() and assertWarnsMessage() instead of assertRaises() and assertWarns() so you can check the exception or warning message. Use assertRaisesRegex() and assertWarnsRegex() only if you need regular expression matching.

    Use assertIs(…, True/False) for testing boolean values, rather than assertTrue() and assertFalse(), so you can check the actual boolean value, not the truthiness of the expression.

  • In test docstrings, state the expected behavior that each test demonstrates. Don’t include preambles such as “Tests that” or “Ensures that”.

    Reserve ticket references for obscure issues where the ticket has additional details that can’t be easily described in docstrings or comments. Include the ticket number at the end of a sentence like this:

    1. def test_foo():
    2. """
    3. A test docstring looks like this (#123456).
    4. """
    5. ...

Imports

  • Use isort to automate import sorting using the guidelines below.

    Quick start:

    / 

    1. $ python -m pip install "isort >= 5.1.0"
    2. $ isort .
    1. ...\> py -m pip install "isort >= 5.1.0"
    2. ...\> isort .

    This runs isort recursively from your current directory, modifying any files that don’t conform to the guidelines. If you need to have imports out of order (to avoid a circular import, for example) use a comment like this:

    1. import module # isort:skip
  • Put imports in these groups: future, standard library, third-party libraries, other Django components, local Django component, try/excepts. Sort lines in each group alphabetically by the full module name. Place all import module statements before from module import objects in each section. Use absolute imports for other Django components and relative imports for local components.

  • On each line, alphabetize the items with the upper case items grouped before the lowercase items.

  • Break long lines using parentheses and indent continuation lines by 4 spaces. Include a trailing comma after the last import and put the closing parenthesis on its own line.

    Use a single blank line between the last import and any module level code, and use two blank lines above the first function or class.

    For example (comments are for explanatory purposes only):

    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 (

    1. Http404,
    2. HttpResponse,
    3. HttpResponseNotAllowed,
    4. StreamingHttpResponse,
    5. cookie,

    )

    local Django

    from .models import LogEntry

    try/except

    try:

    1. import yaml

    except ImportError:

    1. yaml = None

    CONSTANT = “foo”

  1. class Example:
  2. ...
  3. ```
  • Use convenience imports whenever available. For example, do this

    1. from django.views import View

    instead of:

    1. from django.views.generic.base import View

Template style

  • In Django template code, put one (and only one) space between the curly brackets and the tag contents.

    Do this:

    1. {{ foo }}

    Don’t do this:

    1. {{foo}}

View style

  • In Django views, the first parameter in a view function should be called request.

    Do this:

    1. def my_view(request, foo):
    2. ...

    Don’t do this:

    1. def my_view(req, foo):
    2. ...

Model style

  • Field names should be all lowercase, using underscores instead of camelCase.

    Do this:

    1. class Person(models.Model):
    2. first_name = models.CharField(max_length=20)
    3. last_name = models.CharField(max_length=40)

    Don’t do this:

    1. class Person(models.Model):
    2. FirstName = models.CharField(max_length=20)
    3. Last_Name = models.CharField(max_length=40)
  • The class Meta should appear after the fields are defined, with a single blank line separating the fields and the class definition.

    Do this:

    1. class Person(models.Model):
    2. first_name = models.CharField(max_length=20)
    3. last_name = models.CharField(max_length=40)
    4. class Meta:
    5. verbose_name_plural = "people"

    Don’t do this:

    1. class Person(models.Model):
    2. class Meta:
    3. verbose_name_plural = "people"
    4. first_name = models.CharField(max_length=20)
    5. last_name = models.CharField(max_length=40)
  • The order of model inner classes and standard methods should be as follows (noting that these are not all required):

    • All database fields
    • Custom manager attributes
    • class Meta
    • def __str__()
    • def save()
    • def get_absolute_url()
    • Any custom methods
  • If choices is defined 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:

    1. class MyModel(models.Model):
    2. DIRECTION_UP = "U"
    3. DIRECTION_DOWN = "D"
    4. DIRECTION_CHOICES = [
    5. (DIRECTION_UP, "Up"),
    6. (DIRECTION_DOWN, "Down"),
    7. ]

Use of django.conf.settings

Modules should not in general use settings stored in django.conf.settings at the top level (i.e. evaluated when the module is imported). The explanation for this is as follows:

Manual configuration of settings (i.e. not relying on the DJANGO_SETTINGS_MODULE environment variable) is allowed and possible as follows:

  1. from django.conf import settings
  2. settings.configure({}, SOME_SETTING="foo")

However, if any setting is accessed before the settings.configure line, this will not work. (Internally, settings is a LazyObject which configures itself automatically when the settings are accessed if it has not already been configured).

So, if there is a module containing some code as follows:

  1. from django.conf import settings
  2. from django.urls import get_callable
  3. default_foo_view = get_callable(settings.FOO_VIEW)

…then importing this module will cause the settings object to be configured. That means that the ability for third parties to import the module at the top level is incompatible with the ability to configure the settings object manually, or makes it very difficult in some circumstances.

Instead of the above code, a level of laziness or indirection must be used, such as django.utils.functional.LazyObject, django.utils.functional.lazy() or lambda.

Miscellaneous

  • Mark all strings for internationalization; see the i18n documentation for details.
  • Remove import statements that are no longer used when you change code. flake8 will identify these imports for you. If an unused import needs to remain for backwards-compatibility, mark the end of with # NOQA to silence the flake8 warning.
  • Systematically remove all trailing whitespaces from your code as those add unnecessary bytes, add visual clutter to the patches and can also occasionally cause unnecessary merge conflicts. Some IDE’s can be configured to automatically remove them and most VCS tools can be set to highlight them in diff outputs.
  • Please don’t put your name in the code you contribute. Our policy is to keep contributors’ names in the AUTHORS file distributed with Django – not scattered throughout the codebase itself. Feel free to include a change to the AUTHORS file in your patch if you make more than a single trivial change.

JavaScript style

For details about the JavaScript code style used by Django, see JavaScript.