---
title: "Coding style"
version: 2.1
locale: fr
source: https://docs.djangoproject.com/fr/2.1/internals/contributing/writing-code/coding-style/
canonical: https://djangodocs.dev/fr/2.1/internals/contributing/writing-code/coding-style/
---
# Coding style

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

## Python style

- Please conform to the indentation style dictated in the `.editorconfig`
  file. We recommend using a text editor with [EditorConfig](https://editorconfig.org/) 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**](https://peps.python.org/pep-0008/).

  Use [flake8](https://pypi.org/project/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**](https://peps.python.org/pep-0008/) is only a guide, so respect the style of the surrounding code as a
  primary goal.

  An exception to [**PEP 8**](https://peps.python.org/pep-0008/) 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 119 characters as this is the width of GitHub
  code review; anything longer requires horizontal scrolling which makes review
  more difficult. This check is included when you run `flake8`. Documentation,
  comments, and docstrings should be wrapped at 79 characters, even though
  [**PEP 8**](https://peps.python.org/pep-0008/) suggests 72.
- Utilisez 4 espaces pour l’indentation.
- Use four space hanging indentation rather than vertical alignment:

  ```
  raise AttributeError(
      'Here is a multiline error message '
      'shortened for clarity.'
  )
  ```

  Instead of:

  ```
  raise AttributeError('Here is a multiline error message '
                       'shortened for clarity.')
  ```

  This makes better use of space and avoids having to realign strings if the
  length of the first line changes.
- Use single quotes for strings, or a double quote if the string contains a
  single quote. Don’t waste time doing unrelated refactoring of existing code
  to conform to this style.
- 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**](https://peps.python.org/pep-0257/).
- In tests, use
  [`assertRaisesMessage()`](/fr/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertRaisesMessage) and
  [`assertWarnsMessage()`](/fr/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertWarnsMessage)
  instead of [`assertRaises()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises) and
  [`assertWarns()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertWarns) so you can check the
  exception or warning message. Use [`assertRaisesRegex()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaisesRegex)
  and [`assertWarnsRegex()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertWarnsRegex) only if you need regular
  expression matching.
- 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:

  ```
  def test_foo():
      """
      A test docstring looks like this (#123456).
      """
      ...
  ```

## Importations

- Use [isort](https://github.com/timothycrosley/isort#readme) to automate
  import sorting using the guidelines below.

  Quick start:

  ```console
  $ pip install isort
  $ isort -rc .
  ```

  *Windows*

  ```doscon
  ...\> pip install isort
  ...\> isort -rc .
  ```

  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:

  ```
  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.
- Sur chaque ligne, triez les éléments par ordre alphabétique en groupant les noms avec majuscule avant les noms avec minuscule.
- Séparez les longues lignes par des parenthèses et indentez les lignes de continuation par 4 espaces. Ajoutez une virgule finale après la dernière importation et placez la parenthèse fermante sur sa propre ligne.

  Placez une seule ligne vierge entre la dernière importation et tout code de niveau module, et placez deux lignes vierges au-dessus de la première fonction ou classe.

  Par exemple (les commentaires ne sont qu’à titre informatif) :

  *django/contrib/admin/example.py*

  ```python
  # 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:
      # ...
  ```
- Utilisez des importations les plus directes possibles quand elles sont disponibles

  ```
  from django.views import View
  ```

  au lieu de

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

## Style des gabarits

- Dans le code des gabarits Django, placez un et un seul espace entre les accolades et le contenu des balises.

  Faites :

  ```html+django
  {{ foo }}
  ```

  Ne faites pas :

  ```html+django
  {{foo}}
  ```

## Style des vues

- Dans les vues de Django, le premier paramètre d’une vue fonction devrait s’appeler `request`.

  Faites

  ```
  def my_view(request, foo):
      # ...
  ```

  Ne faites pas :

  ```
  def my_view(req, foo):
      # ...
  ```

## Style des modèles

- Les noms de champs devraient être tout en minuscules, en utilisant des soulignements au lieu du StyleChameau.

  Faites

  ```
  class Person(models.Model):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
  ```

  Ne faites pas :

  ```
  class Person(models.Model):
      FirstName = models.CharField(max_length=20)
      Last_Name = models.CharField(max_length=40)
  ```
- La `class Meta` doit apparaître *après* les définitions de champs, avec une seule ligne vierge séparant les champs de la définition de classe.

  Faites

  ```
  class Person(models.Model):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)

      class Meta:
          verbose_name_plural = 'people'
  ```

  Ne faites pas :

  ```
  class Person(models.Model):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
      class Meta:
          verbose_name_plural = 'people'
  ```

  Ne faites pas ça non plus :

  ```
  class Person(models.Model):
      class Meta:
          verbose_name_plural = 'people'

      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=40)
  ```
- L’ordre des classes internes de modèles et des méthodes standards doit être le suivant (notez qu’elles ne sont pas toutes obligatoires) :

  - Tous les champs de la base de données
  - Attributs des gestionnaires personnalisés
  - `class Meta`
  - `def __str__()`
  - `def save()`
  - `def get_absolute_url()`
  - Toute autre méthode personnalisée
- Si `choices` est défini pour un champ de modèle, définissez chaque choix sous forme de tuple de tuples, avec un nom tout en majuscules comme attribut de classe du modèle. Exemple

  ```
  class MyModel(models.Model):
      DIRECTION_UP = 'U'
      DIRECTION_DOWN = 'D'
      DIRECTION_CHOICES = (
          (DIRECTION_UP, 'Up'),
          (DIRECTION_DOWN, 'Down'),
      )
  ```

## Utilisation de `django.conf.settings`

Les modules ne devraient généralement pas utiliser des réglages stockés dans `django.conf.settings` à leur premier niveau (c’est-à-dire évalués au moment de l’importation du module). Voici pourquoi :

La configuration manuelle des réglages (qui ne dépend pas de la variable d’environnement `DJANGO_SETTINGS_MODULE`) est autorisée et possible comme ceci

```
from django.conf import settings

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:

```
from django.conf import settings
from django.urls import get_callable

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`.

## Divers

- Marquez toutes les chaînes à traduire ; voir la  [documentation i18n](/fr/2.1/topics/i18n/) pour plus de détails.
- Remove `import` statements that are no longer used when you change code.
  [flake8](https://pypi.org/project/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.

## Style JavaScript

Pour plus de détails sur le style de code JavaScript utilisé par Django, consultez [JavaScript](/fr/2.1/internals/contributing/writing-code/javascript/).
