| 1 |
============ |
| 2 |
Coding style |
| 3 |
============ |
| 4 |
|
| 5 |
Please follow these coding standards when writing code for inclusion in Django. |
| 6 |
|
| 7 |
.. _coding-style-pre-commit: |
| 8 |
|
| 9 |
Pre-commit checks |
| 10 |
================= |
| 11 |
|
| 12 |
`pre-commit <https://pre-commit.com>`_ is a framework for managing pre-commit |
| 13 |
hooks. These hooks help to identify simple issues before committing code for |
| 14 |
review. By checking for these issues before code review it allows the reviewer |
| 15 |
to focus on the change itself, and it can also help to reduce the number of CI |
| 16 |
runs. |
| 17 |
|
| 18 |
To use the tool, first install ``pre-commit`` and then the git hooks: |
| 19 |
|
| 20 |
.. console:: |
| 21 |
|
| 22 |
$ python -m pip install pre-commit |
| 23 |
$ pre-commit install |
| 24 |
|
| 25 |
On the first commit ``pre-commit`` will install the hooks, these are |
| 26 |
installed in their own environments and will take a short while to |
| 27 |
install on the first run. Subsequent checks will be significantly faster. |
| 28 |
If an error is found an appropriate error message will be displayed. |
| 29 |
If the error was with ``black`` or ``isort`` then the tool will go ahead and |
| 30 |
fix them for you. Review the changes and re-stage for commit if you are happy |
| 31 |
with them. |
| 32 |
|
| 33 |
.. _coding-style-python: |
| 34 |
|
| 35 |
Python style |
| 36 |
============ |
| 37 |
|
| 38 |
* All files should be formatted using the :pypi:`black` auto-formatter. This |
| 39 |
will be run by ``pre-commit`` if that is configured. |
| 40 |
|
| 41 |
* The project repository includes an ``.editorconfig`` file. We recommend using |
| 42 |
a text editor with `EditorConfig`_ support to avoid indentation and |
| 43 |
whitespace issues. The Python files use 4 spaces for indentation and the HTML |
| 44 |
files use 2 spaces. |
| 45 |
|
| 46 |
* Unless otherwise specified, follow :pep:`8`. |
| 47 |
|
| 48 |
Use :pypi:`flake8` to check for problems in this area. Note that our |
| 49 |
``.flake8`` file excludes some errors that we don't consider as gross |
| 50 |
violations. Remember that :pep:`8` is only a guide, so respect the style of |
| 51 |
the surrounding code as a primary goal. |
| 52 |
|
| 53 |
An exception to :pep:`8` is our rules on line lengths. Don't limit lines of |
| 54 |
code to 79 characters if it means the code looks significantly uglier or is |
| 55 |
harder to read. We allow up to 88 characters as this is the line length used |
| 56 |
by ``black``. This check is included when you run ``flake8``. Documentation, |
| 57 |
comments, and docstrings should be wrapped at 79 characters, even though |
| 58 |
:pep:`8` suggests 72. |
| 59 |
|
| 60 |
* String variable interpolation may use |
| 61 |
:py:ref:`%-formatting <old-string-formatting>`, :py:ref:`f-strings |
| 62 |
<f-strings>`, or :py:meth:`str.format` as appropriate, with the goal of |
| 63 |
maximizing code readability. |
| 64 |
|
| 65 |
Final judgments of readability are left to the Merger's discretion. As a |
| 66 |
guide, f-strings should use only plain variable and property access, with |
| 67 |
prior local variable assignment for more complex cases:: |
| 68 |
|
| 69 |
# Allowed |
| 70 |
f"hello {user}" |
| 71 |
f"hello {user.name}" |
| 72 |
f"hello {self.user.name}" |
| 73 |
|
| 74 |
# Disallowed |
| 75 |
f"hello {get_user()}" |
| 76 |
f"you are {user.age * 365.25} days old" |
| 77 |
|
| 78 |
# Allowed with local variable assignment |
| 79 |
user = get_user() |
| 80 |
f"hello {user}" |
| 81 |
user_days_old = user.age * 365.25 |
| 82 |
f"you are {user_days_old} days old" |
| 83 |
|
| 84 |
f-strings should not be used for any string that may require translation, |
| 85 |
including error and logging messages. In general ``format()`` is more |
| 86 |
verbose, so the other formatting methods are preferred. |
| 87 |
|
| 88 |
Don't waste time doing unrelated refactoring of existing code to adjust the |
| 89 |
formatting method. |
| 90 |
|
| 91 |
* Avoid use of "we" in comments, e.g. "Loop over" rather than "We loop over". |
| 92 |
|
| 93 |
* Use underscores, not camelCase, for variable, function and method names |
| 94 |
(i.e. ``poll.get_unique_voters()``, not ``poll.getUniqueVoters()``). |
| 95 |
|
| 96 |
* Use ``InitialCaps`` for class names (or for factory functions that |
| 97 |
return classes). |
| 98 |
|
| 99 |
* In docstrings, follow the style of existing docstrings and :pep:`257`. |
| 100 |
|
| 101 |
* In tests, use |
| 102 |
:meth:`~django.test.SimpleTestCase.assertRaisesMessage` and |
| 103 |
:meth:`~django.test.SimpleTestCase.assertWarnsMessage` |
| 104 |
instead of :meth:`~unittest.TestCase.assertRaises` and |
| 105 |
:meth:`~unittest.TestCase.assertWarns` so you can check the |
| 106 |
exception or warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex` |
| 107 |
and :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular |
| 108 |
expression matching. |
| 109 |
|
| 110 |
Use :meth:`assertIs(…, True/False)<unittest.TestCase.assertIs>` for testing |
| 111 |
boolean values, rather than :meth:`~unittest.TestCase.assertTrue` and |
| 112 |
:meth:`~unittest.TestCase.assertFalse`, so you can check the actual boolean |
| 113 |
value, not the truthiness of the expression. |
| 114 |
|
| 115 |
* In test docstrings, state the expected behavior that each test demonstrates. |
| 116 |
Don't include preambles such as "Tests that" or "Ensures that". |
| 117 |
|
| 118 |
Reserve ticket references for obscure issues where the ticket has additional |
| 119 |
details that can't be easily described in docstrings or comments. Include the |
| 120 |
ticket number at the end of a sentence like this:: |
| 121 |
|
| 122 |
def test_foo(): |
| 123 |
""" |
| 124 |
A test docstring looks like this (#123456). |
| 125 |
""" |
| 126 |
... |
| 127 |
|
| 128 |
* Where applicable, use unpacking generalizations compliant with :pep:`448`, |
| 129 |
such as merging mappings (``{**x, **y}``) or sequences (``[*a, *b]``). This |
| 130 |
improves performance, readability, and maintainability while reducing errors. |
| 131 |
|
| 132 |
.. _coding-style-imports: |
| 133 |
|
| 134 |
Imports |
| 135 |
======= |
| 136 |
|
| 137 |
* Use :pypi:`isort` to automate import sorting using the guidelines below. |
| 138 |
|
| 139 |
Quick start: |
| 140 |
|
| 141 |
.. console:: |
| 142 |
|
| 143 |
$ python -m pip install "isort >= 7.0.0" |
| 144 |
$ isort . |
| 145 |
|
| 146 |
This runs ``isort`` recursively from your current directory, modifying any |
| 147 |
files that don't conform to the guidelines. If you need to have imports out |
| 148 |
of order (to avoid a circular import, for example) use a comment like this:: |
| 149 |
|
| 150 |
import module # isort:skip |
| 151 |
|
| 152 |
* Put imports in these groups: future, standard library, third-party libraries, |
| 153 |
other Django components, local Django component, try/excepts. Sort lines in |
| 154 |
each group alphabetically by the full module name. Place all ``import module`` |
| 155 |
statements before ``from module import objects`` in each section. Use absolute |
| 156 |
imports for other Django components and relative imports for local components. |
| 157 |
|
| 158 |
* On each line, alphabetize the items with the upper case items grouped before |
| 159 |
the lowercase items. |
| 160 |
|
| 161 |
* Break long lines using parentheses and indent continuation lines by 4 spaces. |
| 162 |
Include a trailing comma after the last import and put the closing |
| 163 |
parenthesis on its own line. |
| 164 |
|
| 165 |
Use a single blank line between the last import and any module level code, |
| 166 |
and use two blank lines above the first function or class. |
| 167 |
|
| 168 |
For example (comments are for explanatory purposes only): |
| 169 |
|
| 170 |
.. code-block:: python |
| 171 |
:caption: ``django/contrib/admin/example.py`` |
| 172 |
|
| 173 |
# future |
| 174 |
from __future__ import unicode_literals |
| 175 |
|
| 176 |
# standard library |
| 177 |
import json |
| 178 |
from itertools import chain |
| 179 |
|
| 180 |
# third-party |
| 181 |
import bcrypt |
| 182 |
|
| 183 |
# Django |
| 184 |
from django.http import Http404 |
| 185 |
from django.http.response import ( |
| 186 |
Http404, |
| 187 |
HttpResponse, |
| 188 |
HttpResponseNotAllowed, |
| 189 |
StreamingHttpResponse, |
| 190 |
cookie, |
| 191 |
) |
| 192 |
|
| 193 |
# local Django |
| 194 |
from .models import LogEntry |
| 195 |
|
| 196 |
# try/except |
| 197 |
try: |
| 198 |
import yaml |
| 199 |
except ImportError: |
| 200 |
yaml = None |
| 201 |
|
| 202 |
CONSTANT = "foo" |
| 203 |
|
| 204 |
|
| 205 |
class Example: ... |
| 206 |
|
| 207 |
* Use convenience imports whenever available. For example, do this |
| 208 |
:: |
| 209 |
|
| 210 |
from django.views import View |
| 211 |
|
| 212 |
instead of:: |
| 213 |
|
| 214 |
from django.views.generic.base import View |
| 215 |
|
| 216 |
Template style |
| 217 |
============== |
| 218 |
|
| 219 |
Follow the below rules in Django template code. |
| 220 |
|
| 221 |
* ``{% extends %}`` should be the first non-comment line. |
| 222 |
|
| 223 |
Do this: |
| 224 |
|
| 225 |
.. code-block:: html+django |
| 226 |
|
| 227 |
{% extends "base.html" %} |
| 228 |
|
| 229 |
{% block content %} |
| 230 |
<h1 class="font-semibold text-xl"> |
| 231 |
{{ pages.title }} |
| 232 |
</h1> |
| 233 |
{% endblock content %} |
| 234 |
|
| 235 |
Or this: |
| 236 |
|
| 237 |
.. code-block:: html+django |
| 238 |
|
| 239 |
{# This is a comment #} |
| 240 |
{% extends "base.html" %} |
| 241 |
|
| 242 |
{% block content %} |
| 243 |
<h1 class="font-semibold text-xl"> |
| 244 |
{{ pages.title }} |
| 245 |
</h1> |
| 246 |
{% endblock content %} |
| 247 |
|
| 248 |
Don't do this: |
| 249 |
|
| 250 |
.. code-block:: html+django |
| 251 |
|
| 252 |
{% load i18n %} |
| 253 |
{% extends "base.html" %} |
| 254 |
|
| 255 |
{% block content %} |
| 256 |
<h1 class="font-semibold text-xl"> |
| 257 |
{{ pages.title }} |
| 258 |
</h1> |
| 259 |
{% endblock content %} |
| 260 |
|
| 261 |
* Put exactly one space between ``{{``, variable contents, and ``}}``. |
| 262 |
|
| 263 |
Do this: |
| 264 |
|
| 265 |
.. code-block:: html+django |
| 266 |
|
| 267 |
{{ user }} |
| 268 |
|
| 269 |
Don't do this: |
| 270 |
|
| 271 |
.. code-block:: html+django |
| 272 |
|
| 273 |
{{user}} |
| 274 |
|
| 275 |
* In ``{% load ... %}``, list libraries in alphabetical order. |
| 276 |
|
| 277 |
Do this: |
| 278 |
|
| 279 |
.. code-block:: html+django |
| 280 |
|
| 281 |
{% load i18n l10 tz %} |
| 282 |
|
| 283 |
Don't do this: |
| 284 |
|
| 285 |
.. code-block:: html+django |
| 286 |
|
| 287 |
{% load l10 i18n tz %} |
| 288 |
|
| 289 |
* Put exactly one space between ``{%``, tag contents, and ``%}``. |
| 290 |
|
| 291 |
Do this: |
| 292 |
|
| 293 |
.. code-block:: html+django |
| 294 |
|
| 295 |
{% load humanize %} |
| 296 |
|
| 297 |
Don't do this: |
| 298 |
|
| 299 |
.. code-block:: html+django |
| 300 |
|
| 301 |
{%load humanize%} |
| 302 |
|
| 303 |
* Put the ``{% block %}`` tag name in the ``{% endblock %}`` tag if it is not |
| 304 |
on the same line. |
| 305 |
|
| 306 |
Do this: |
| 307 |
|
| 308 |
.. code-block:: html+django |
| 309 |
|
| 310 |
{% block header %} |
| 311 |
|
| 312 |
Code goes here |
| 313 |
|
| 314 |
{% endblock header %} |
| 315 |
|
| 316 |
Don't do this: |
| 317 |
|
| 318 |
.. code-block:: html+django |
| 319 |
|
| 320 |
{% block header %} |
| 321 |
|
| 322 |
Code goes here |
| 323 |
|
| 324 |
{% endblock %} |
| 325 |
|
| 326 |
* Inside curly braces, separate tokens by single spaces, except for around the |
| 327 |
``.`` for attribute access and the ``|`` for a filter. |
| 328 |
|
| 329 |
Do this: |
| 330 |
|
| 331 |
.. code-block:: html+django |
| 332 |
|
| 333 |
{% if user.name|lower == "admin" %} |
| 334 |
|
| 335 |
Don't do this: |
| 336 |
|
| 337 |
.. code-block:: html+django |
| 338 |
|
| 339 |
{% if user . name | lower == "admin" %} |
| 340 |
|
| 341 |
{{ user.name | upper }} |
| 342 |
|
| 343 |
* Within a template using ``{% extends %}``, avoid indenting top-level |
| 344 |
``{% block %}`` tags. |
| 345 |
|
| 346 |
Do this: |
| 347 |
|
| 348 |
.. code-block:: html+django |
| 349 |
|
| 350 |
{% extends "base.html" %} |
| 351 |
|
| 352 |
{% block content %} |
| 353 |
|
| 354 |
Don't do this: |
| 355 |
|
| 356 |
.. code-block:: html+django |
| 357 |
|
| 358 |
{% extends "base.html" %} |
| 359 |
|
| 360 |
{% block content %} |
| 361 |
... |
| 362 |
|
| 363 |
View style |
| 364 |
========== |
| 365 |
|
| 366 |
* In Django views, the first parameter in a view function should be called |
| 367 |
``request``. |
| 368 |
|
| 369 |
Do this:: |
| 370 |
|
| 371 |
def my_view(request, foo): ... |
| 372 |
|
| 373 |
Don't do this:: |
| 374 |
|
| 375 |
def my_view(req, foo): ... |
| 376 |
|
| 377 |
Model style |
| 378 |
=========== |
| 379 |
|
| 380 |
* Field names should be all lowercase, using underscores instead of |
| 381 |
camelCase. |
| 382 |
|
| 383 |
Do this:: |
| 384 |
|
| 385 |
class Person(models.Model): |
| 386 |
first_name = models.CharField(max_length=20) |
| 387 |
last_name = models.CharField(max_length=40) |
| 388 |
|
| 389 |
Don't do this:: |
| 390 |
|
| 391 |
class Person(models.Model): |
| 392 |
FirstName = models.CharField(max_length=20) |
| 393 |
Last_Name = models.CharField(max_length=40) |
| 394 |
|
| 395 |
* The ``class Meta`` should appear *after* the fields are defined, with |
| 396 |
a single blank line separating the fields and the class definition. |
| 397 |
|
| 398 |
Do this:: |
| 399 |
|
| 400 |
class Person(models.Model): |
| 401 |
first_name = models.CharField(max_length=20) |
| 402 |
last_name = models.CharField(max_length=40) |
| 403 |
|
| 404 |
class Meta: |
| 405 |
verbose_name_plural = "people" |
| 406 |
|
| 407 |
Don't do this:: |
| 408 |
|
| 409 |
class Person(models.Model): |
| 410 |
class Meta: |
| 411 |
verbose_name_plural = "people" |
| 412 |
|
| 413 |
first_name = models.CharField(max_length=20) |
| 414 |
last_name = models.CharField(max_length=40) |
| 415 |
|
| 416 |
* The order of model inner classes and standard methods should be as |
| 417 |
follows (noting that these are not all required): |
| 418 |
|
| 419 |
* All database fields |
| 420 |
* Custom manager attributes |
| 421 |
* ``class Meta`` |
| 422 |
* ``def __str__()`` and other Python magic methods |
| 423 |
* ``def save()`` |
| 424 |
* ``def get_absolute_url()`` |
| 425 |
* Any custom methods |
| 426 |
|
| 427 |
* If ``choices`` is defined for a given model field, define each choice as a |
| 428 |
mapping, with an all-uppercase name as a class attribute on the model. |
| 429 |
Example:: |
| 430 |
|
| 431 |
class MyModel(models.Model): |
| 432 |
DIRECTION_UP = "U" |
| 433 |
DIRECTION_DOWN = "D" |
| 434 |
DIRECTION_CHOICES = { |
| 435 |
DIRECTION_UP: "Up", |
| 436 |
DIRECTION_DOWN: "Down", |
| 437 |
} |
| 438 |
|
| 439 |
Alternatively, consider using :ref:`field-choices-enum-types`:: |
| 440 |
|
| 441 |
class MyModel(models.Model): |
| 442 |
class Direction(models.TextChoices): |
| 443 |
UP = "U", "Up" |
| 444 |
DOWN = "D", "Down" |
| 445 |
|
| 446 |
Use of ``django.conf.settings`` |
| 447 |
=============================== |
| 448 |
|
| 449 |
Modules should not in general use settings stored in ``django.conf.settings`` |
| 450 |
at the top level (i.e. evaluated when the module is imported). The explanation |
| 451 |
for this is as follows: |
| 452 |
|
| 453 |
Manual configuration of settings (i.e. not relying on the |
| 454 |
:envvar:`DJANGO_SETTINGS_MODULE` environment variable) is allowed and possible |
| 455 |
as follows:: |
| 456 |
|
| 457 |
from django.conf import settings |
| 458 |
|
| 459 |
settings.configure({}, SOME_SETTING="foo") |
| 460 |
|
| 461 |
However, if any setting is accessed before the ``settings.configure`` line, |
| 462 |
this will not work. (Internally, ``settings`` is a ``LazyObject`` which |
| 463 |
configures itself automatically when the settings are accessed if it has not |
| 464 |
already been configured). |
| 465 |
|
| 466 |
So, if there is a module containing some code as follows:: |
| 467 |
|
| 468 |
from django.conf import settings |
| 469 |
from django.urls import get_callable |
| 470 |
|
| 471 |
default_foo_view = get_callable(settings.FOO_VIEW) |
| 472 |
|
| 473 |
...then importing this module will cause the settings object to be configured. |
| 474 |
That means that the ability for third parties to import the module at the top |
| 475 |
level is incompatible with the ability to configure the settings object |
| 476 |
manually, or makes it very difficult in some circumstances. |
| 477 |
|
| 478 |
Instead of the above code, a level of laziness or indirection must be used, |
| 479 |
such as ``django.utils.functional.LazyObject``, |
| 480 |
``django.utils.functional.lazy()`` or ``lambda``. |
| 481 |
|
| 482 |
Miscellaneous |
| 483 |
============= |
| 484 |
|
| 485 |
* Mark all strings for internationalization; see the :doc:`i18n |
| 486 |
documentation </topics/i18n/index>` for details. |
| 487 |
|
| 488 |
* Remove ``import`` statements that are no longer used when you change code. |
| 489 |
:pypi:`flake8` will identify these imports for you. If an unused import needs |
| 490 |
to remain for backwards-compatibility, mark the end of with ``# NOQA`` to |
| 491 |
silence the flake8 warning. |
| 492 |
|
| 493 |
* Systematically remove all trailing whitespaces from your code as those |
| 494 |
add unnecessary bytes, add visual clutter to the patches and can also |
| 495 |
occasionally cause unnecessary merge conflicts. Some IDE's can be |
| 496 |
configured to automatically remove them and most VCS tools can be set to |
| 497 |
highlight them in diff outputs. |
| 498 |
|
| 499 |
* Please don't put your name in the code you contribute. Our policy is to |
| 500 |
keep contributors' names in the ``AUTHORS`` file distributed with Django |
| 501 |
-- not scattered throughout the codebase itself. Feel free to include a |
| 502 |
change to the ``AUTHORS`` file in your patch if you make more than a |
| 503 |
single trivial change. |
| 504 |
|
| 505 |
JavaScript style |
| 506 |
================ |
| 507 |
|
| 508 |
For details about the JavaScript code style used by Django, see |
| 509 |
:doc:`javascript`. |
| 510 |
|
| 511 |
.. _editorconfig: https://editorconfig.org/ |