---
title: "Notes de publication de Django 1.7"
version: 3.1
locale: fr
source: https://docs.djangoproject.com/fr/3.1/releases/1.7/
canonical: https://djangodocs.dev/fr/3.1/releases/1.7/
---
# Notes de publication de Django 1.7

*2 Septembre 2014*

Bienvenue dans Django 1.7 !

These release notes cover the [new features](#whats-new-1-7), as well as
some [backwards incompatible changes](#backwards-incompatible-1-7) you’ll
want to be aware of when upgrading from Django 1.6 or older versions. We’ve
[begun the deprecation process for some features](#deprecated-features-1-7), and some features have reached the end of their
deprecation process and [have been removed](#removed-features-1-7).

## Compatibilité Python

Django 1.7 requires Python 2.7, 3.2, 3.3, or 3.4. We **highly recommend** and
only officially support the latest release of each series.

The Django 1.6 series is the last to support Python 2.6. Django 1.7 is the
first release to support Python 3.4.

Ce changement devrait affecter seulement un petit nombre d’utilisateurs de Django, puisque, aujourd’hui, la plupart des fournisseurs de système d’exploitation livrent Python 2.7 ou plus récent comme version par défaut. Cependant, si vous utilisez encore Python 2.6, vous aurez besoin de rester à Django 1.6 jusqu’à ce que vous puissiez mettre à jour votre version de Python. Selon [notre politique de support](/fr/3.1/internals/release-process/), Django 1.6 continuera d’être supporté au niveau sécurité jusqu’à la sortie de Django 1.8.

## Quoi de neuf dans Django 1.7

### Migrations de schéma

Django a maintenant un support intégré des migrations de schéma. Il permet aux modèles d’être mis à jour, modifiés et supprimés par la création de fichiers de migration qui représentent les changements du modèle et qui peuvent être exécutés sur toute base de données de développement, de pré-production ou de production.

Les migrations sont couvertes dans [leur propre documentation](/fr/3.1/topics/migrations/), mais quelques-unes des fonctionalités clés sont :

- `syncdb` a été dépréciée et remplacée par `migrate`. Ne vous inquiétez pas – les appels à `syncdb` fonctionneront toujours comme avant.
- Une nouvelle commande `makemigrations` fournit un moyen facile de détecter automatiquement les modifications de vos modèles et d’effectuer des migrations pour ceux-ci.

  `django.db.models.signals.pre_syncdb` and
  `django.db.models.signals.post_syncdb` have been deprecated,
  to be replaced by [`pre_migrate`](/fr/3.1/ref/signals/#django.db.models.signals.pre_migrate) and
  [`post_migrate`](/fr/3.1/ref/signals/#django.db.models.signals.post_migrate) respectively. These
  new signals have slightly different arguments. Check the
  documentation for details.
- La méthode `allow_syncdb` des routeurs de base de données est désormais appelé `allow_migrate`, mais effectue toujours la même fonction. Les routeurs avec des méthodes `allow_syncdb` fonctionneront toujours, mais ce nom de méthode est obsolète et vous devriez en changer dès que possible (rien de plus que le renommage est nécessaire).
- `initial_data` fixtures are no longer loaded for apps with migrations; if
  you want to load initial data for an app, we suggest you create a migration for
  your application and define a [`RunPython`](/fr/3.1/ref/migration-operations/#django.db.migrations.operations.RunPython)
  or [`RunSQL`](/fr/3.1/ref/migration-operations/#django.db.migrations.operations.RunSQL) operation in the `operations` section of the migration.
- Le comportement de restauration du test est différent pour les applications avec des migrations; en particulier, Django n’émulera plus les restaurations pour les bases de données non transactionnelles ou à l’intérieur de `TransactionTestCase` [sauf demande expresse](/fr/3.1/topics/testing/overview/#test-case-serialized-rollback).
- It is not advised to have apps without migrations depend on (have a
  [`ForeignKey`](/fr/3.1/ref/models/fields/#django.db.models.ForeignKey) or
  [`ManyToManyField`](/fr/3.1/ref/models/fields/#django.db.models.ManyToManyField) to) apps with migrations.

### Réusinage du chargement des applications

Historiquement, les applications Django étaient étroitement liés aux modèles. Un singleton connu comme le « app cache » gérait à la fois les applications et les modèles installés. Le module de modèles était utilisé comme un identificateur pour les applications dans de nombreuses API.

Étant donné que le concept d”[applications Django](/fr/3.1/ref/applications/) mûrit, ce code a montré certaines lacunes. Il a été remanié en un « app registry » où les modules de modèles n’ont plus un rôle central et où il est possible de joindre des données de configuration aux applications.

Les améliorations comprennent à ce jour :

- Les applications peuvent exécuter du code au démarrage, avant que Django ne fasse quoi que ce soit d’autre, avec la méthode [`ready()`](/fr/3.1/ref/applications/#django.apps.AppConfig.ready) de leur configuration.
- Les étiquettes d’application sont correctement affectées à des modèles, même quand ils sont définis en dehors de `models.py`. Vous n’avez plus besoin de régler explicitement [`app_label`](/fr/3.1/ref/models/options/#django.db.models.Options.app_label).
- Il est possible d’omettre `models.py` entièrement si une application ne possède pas de modèles.
- Les applications peuvent être rebaptisées avec l’attribut [`label`](/fr/3.1/ref/applications/#django.apps.AppConfig.label) des configurations d’application, afin de contourner des conflits de nommage d’étiquettes.
- Le nom des applications peut être personnalisé dans l’interface d’administration avec l’attribut [`verbose_name`](/fr/3.1/ref/applications/#django.apps.AppConfig.verbose_name) des configurations d’application.
- L’interface d’administration appelle automatiquement [`autodiscover()`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.autodiscover) au lancement de Django. Vous pouvez donc supprimer cette ligne de votre URLconf.
- Django importe toutes les configurations d’application et les modèles dès qu’il se lance, au travers d’un processus déterministe et simple. Cela devrait rendre plus facile de diagnostiquer des problèmes d’importation tels que des boucles d’importation.

### Nouvelle méthode sur les sous-classes de Field

Pour aider à motoriser à la fois les migrations de schéma et permettre l’ajout plus simple de clés composites dans les futures versions de Django, l’API de [`Field`](/fr/3.1/ref/models/fields/#django.db.models.Field) a maintenant une nouvelle méthode obligatoire : `deconstruct()`.

Cette méthode ne prend aucun argument, et retourne un tuple de quatre éléments :

- `name`: The field’s attribute name on its parent model, or `None` if it
  is not part of a model
- `path` : Un chemin Python à syntaxe pointée vers la classe de ce champ, y compris le nom de la classe.
- `args` : arguments positionnels, en tant que liste
- `kwargs` : arguments nommés, en tant que dict

Ces quatre valeurs permettent à n’importe quel champ d’être sérialisé dans un fichier, ainsi que d’être copié en toute sécurité, deux parties essentielles de ces nouvelles fonctionnalités.

Ce changement ne devrait pas vous affecter à moins que vous n’écriviez des sous-classes personnalisées de Field; si c’est le cas, vous devrez peut-être ré-implémenter la méthode `deconstruct()` si votre sous-classe modifie la signature de la méthode `__init__` d’une manière ou d’une autre. Si votre champ hérite juste d’un champ intégré dans Django et n’étend pas `__init__`, aucune modification n’est nécessaire.

Si vous avez besoin d’étendre `deconstruct()`, un bon endroit pour commencer sont les champs intégrés dans Django (`django/db/models/fields/__init__.py`) car plusieurs champs, y compris `DecimalField` et `DateField`, l’étendent et montrent comment appeler la méthode sur la classe mère et simplement ajouter ou supprimer des arguments supplémentaires.

Cela signifie également que tous les arguments de champs doivent eux-mêmes être sérialisable; pour voir ce que nous considérons comme sérialisable, et trouver comment rendre vos propres classes sérialisables, consultez la [documentation de sérialisation de la migration](/fr/3.1/topics/migrations/#migration-serializing).

### Appel personnalisé de méthodes `QuerySet` depuis le `Manager`

Historiquement, la méthode recommandée pour réaliser des requêtes de modèles réutilisables était de créer des méthodes sur une classe `Manager` personnalisée. Le problème avec cette approche est qu’après le premier appel de méthode, vous obtenez une instance de `QuerySet` et ne pouvez pas appeler de méthodes supplémentaires du gestionnaire personnalisé.

Bien que n’étant pas documentée, il était courant de contourner ce problème en créant une `QuerySet` personnalisée afin que les méthodes personnalisées puissent être chaînées; mais la solution avait un certain nombre d’inconvénients :

- La `QuerySet` personnalisée et ses méthodes sur mesure étaient perdues après le premier appel à `values()` ou `values_list()`.
- La rédaction d’un `Manager` sur mesure était encore nécessaire afin de retourner la classe `QuerySet` personnalisée et toutes les méthodes souhaitées sur le \`\` Manager\`\` devaient être redirigées vers la `QuerySet`. L’ensemble du processus était contraire au principe DRY.

La méthode de classe [`QuerySet.as_manager()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.as_manager) peut désormais directement [créer un Manager avec des méthodes de QuerySet](/fr/3.1/topics/db/managers/#create-manager-with-queryset-methods) :

```
class FoodQuerySet(models.QuerySet):
    def pizzas(self):
        return self.filter(kind='pizza')

    def vegetarian(self):
        return self.filter(vegetarian=True)

class Food(models.Model):
    kind = models.CharField(max_length=50)
    vegetarian = models.BooleanField(default=False)
    objects = FoodQuerySet.as_manager()

Food.objects.pizzas().vegetarian()
```

### Utilisation d’un gestionnaire personnalisé lors de la traversée des relations inverses

Il est maintenant possible de [spécifier un gestionnaire personnalisé](/fr/3.1/topics/db/queries/#using-custom-reverse-manager) lors de la traversée d’une relation inverse :

```
class Blog(models.Model):
    pass

class Entry(models.Model):
    blog = models.ForeignKey(Blog)

    objects = models.Manager()  # Default Manager
    entries = EntryManager()    # Custom Manager

b = Blog.objects.get(id=1)
b.entry_set(manager='entries').all()
```

### Nouvelle infrastructure de vérification système

Nous avons ajouté une nouvelle [infrastructure de contrôle du système](/fr/3.1/ref/checks/) pour détecter les problèmes communs (comme les modèles non valides) et de fournir des conseils pour la résolution de ces problèmes. L’infrastructure est extensible de sorte que vous pouvez ajouter vos propres contrôles pour vos propres applications et bibliothèques.

To perform system checks, you use the [`check`](/fr/3.1/ref/django-admin/#django-admin-check) management command.
This command replaces the older `validate` management command.

### Nouvel objet `Prefetch` pour les opérations `prefetch_related` avancées.

Le nouvel objet [`Prefetch`](/fr/3.1/ref/models/querysets/#django.db.models.Prefetch) permet de personnaliser les opérations de préchargement.

Vous pouvez spécifier la `QuerySet` utilisée pour traverser une relation donnée ou personnaliser l’emplacement de stockage des résultats préchargés.

Cela permet des choses comme le filtrage de relations préchargées, en appelant [`select_related()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related) à partir d’une relation préchargée, ou le préchargement de la même relation plusieurs fois avec différentes querysets. Voir [`prefetch_related()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related) pour plus de détails.

### Les raccourcis de l’interface d’administration supporte les fuseaux horaires

Les raccourcis « today » et « now » à côté des composants de saisie de la date et de l’heure dans l’interface d’administration, opèrent désormais dans le [fuseau horaire courant](/fr/3.1/topics/i18n/timezones/#default-current-time-zone). Auparavant, ils utilisaient le fuseau horaire du navigateur, ce qui pouvait entraîner la saisie de valeurs erronées quand il ne correspondait pas au fuseau horaire courant du serveur.

En outre, les composants affichent désormais un message d’aide lorsque le fuseau horaire du navigateur et du serveur diffèrent, afin de préciser comment la valeur insérée dans le champ sera interprétée.

### Utilisation de curseurs de base de données en tant que gestionnaires de contexte

Avant Python 2.7, les curseurs de base de données pouvaient être utilisés en tant que gestionnaire de contexte. Le curseur spécifique au moteur défini le comportement du gestionnaire de contexte. Le comportement des recherches de méthode magique a été modifié avec Python 2.7 et les curseurs ne sont plus utilisables en tant que gestionnaire de contexte.

Django 1.7 permet qu’un curseur soit utilisé comme gestionnaire de contexte. Autrement dit, ce qui suit peut être utilisé :

```
with connection.cursor() as c:
    c.execute(...)
```

au lieu de :

```
c = connection.cursor()
try:
    c.execute(...)
finally:
    c.close()
```

### Expressions de recherche personnalisées

It is now possible to write custom lookups and transforms for the ORM.
Custom lookups work just like Django’s built-in lookups (e.g. `lte`,
`icontains`) while transforms are a new concept.

La classe [`django.db.models.Lookup`](/fr/3.1/ref/models/lookups/#django.db.models.Lookup) fournit un moyen d’ajouter des opérateurs de recherches pour les champs du modèle. A titre d’exemple il est possible d’ajouter l’opérateur `day_lte` pour les `DateFields`.

La classe [`django.db.models.Transform`](/fr/3.1/ref/models/lookups/#django.db.models.Transform) permet la transformation des valeurs de base de données avant la conversion finale. Par exemple, il est possible d’écrire une transformation `year` qui extrait l’année de la valeur du champ. Les transformations permettent le chaînage. Après que la transformation `year` ait été ajoutée à `DateField` il est possible de filtrer sur la valeur transformée, par exemple `qs.filter(author__birthdate__year__lte=1981)`.

Pour plus d’informations sur à la fois les expressions de recherches et les transformations personnalisées reportez-vous à la documentation sur les [recherches personnalisées](/fr/3.1/howto/custom-lookups/).

### Améliorations apportées à la gestion d’erreur dans `Form`

#### `Form.add_error()`

Auparavant, il y avait deux principaux modèles de gestion des erreurs dans les formulaires :

- Lever une [`ValidationError`](/fr/3.1/ref/exceptions/#django.core.exceptions.ValidationError) à partir de certaines fonctions (e.g. `Field.clean()`, `Form.clean_<fieldname>()`, ou `Form.clean()` pour les erreurs n’ayant pas attrait aux champs)
- Manipuler `Form._errors` en ciblant un champ spécifique dans `Form.clean()` ou en ajoutant des erreurs via une méthode « clean » externe (e.g.i, directement depuis une vue).

L’utilisation de la première pratique était simple et directe puisque le formulaire peut deviner à partir du contexte (i.e. quelle méthode a soulevé l’exception) d’où proviennent les erreurs et les traiter automatiquement. Cela reste la manière canonique d’ajouter des erreurs lorsque possible. Cependant, la dernière était fastidieuse et source d’erreurs, car l’essentiel du traitement des effets de bord incombait à l’utilisateur.

La nouvelle méthode [`add_error()`](/fr/3.1/ref/forms/api/#django.forms.Form.add_error) permet d’ajouter des erreurs à des champs de formulaire spécifiques de n’importe où, sans avoir à se soucier des détails; tels que la création d’instances de `django.forms.utils.ErrorList` ou le traitement de `Form.cleaned_data`. Cette nouvelle API remplace la manipulation de `Form._errors` qui devient désormais une API privée.

Voir la [Nettoyage et validation de champs qui dépendent l’un de l’autre](/fr/3.1/ref/forms/validation/#validating-fields-with-clean) pour un exemple utilisant `Form.add_error()`.

#### Métadonnées d’erreur

Le constructeur de [`ValidationError`](/fr/3.1/ref/exceptions/#django.core.exceptions.ValidationError) accepte des métadonnées telles que le `code` d’erreur ou `params` qui sont alors disponibles pour être interpolés dans le message d’erreur (voir [Génération de ValidationError](/fr/3.1/ref/forms/validation/#raising-validation-error) pour plus de détails); toutefois, avant Django 1.7 ces métadonnées étaient rejetées au moment où les erreurs étaient ajoutées à [`Form.errors`](/fr/3.1/ref/forms/api/#django.forms.Form.errors).

[`Form.errors`](/fr/3.1/ref/forms/api/#django.forms.Form.errors) et `django.forms.utils.ErrorList` stockent maintenant les instances de `ValidationError`, donc ces métadonnées peuvent être récupérées à tout moment grâce à la nouvelle méthode [`Form.errors.as_data`](/fr/3.1/ref/forms/api/#django.forms.Form.errors.as_data).

Les instances de `ValidationError` récupérées peuvent alors être identifiées grâce à leur `code` d’erreur qui permet des choses telle que la réécriture du message d’erreur ou l’écriture d’une logique personnalisée dans une vue lorsqu’une erreur donnée est présente. Elle peut également être utilisée pour sérialiser les erreurs dans un format personnalisé tel que XML.

La nouvelle méthode [`Form.errors.as_json()`](/fr/3.1/ref/forms/api/#django.forms.Form.errors.as_json) est une méthode pratique qui renvoie les messages d’erreur ainsi que les codes d’erreur sérialisés en JSON. `as_json()` utilise `as_data()` et donne une idée de la manière dont le nouveau système pourrait être étendu.

#### Conteneurs d’erreur et rétro-compatibilité

Des changements profonds au niveau des différents conteneurs d’erreur furent nécessaires afin de supporter les caractéristiques ci-dessus, à savoir [`Form.errors`](/fr/3.1/ref/forms/api/#django.forms.Form.errors), `Django.forms.utils.ErrorList`, et les stockages interne de [`ValidationError`](/fr/3.1/ref/exceptions/#django.core.exceptions.ValidationError). Ces conteneurs auparavant utilisés pour stocker des chaînes d’erreur stockent désormais des instances de `ValidationError` et les API publiques ont été adaptées pour rendre cela aussi transparent que possible, mais si vous avez utilisé les API privées, certains des changements ne sont pas rétro-compatibles; voir [ValidationError constructor and internal storage](#validation-error-constructor-and-internal-storage) pour plus de détails.

### Fonctionnalités mineures

#### [`django.contrib.admin`](/fr/3.1/ref/contrib/admin/#module-django.contrib.admin)

- Vous pouvez maintenant implémenter les attributs [`site_header`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.AdminSite.site_header), [`site_title`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.AdminSite.site_title) et [`index_title`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.AdminSite.index_title)  sur un [`AdminSite`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.AdminSite) personnalisé afin de changer facilement le titre et le texte d’en-tête de page du site d’administration. Plus besoin d’étendre les gabarits !
- Les boutons dans [`django.contrib.admin`](/fr/3.1/ref/contrib/admin/#module-django.contrib.admin) utilise maintenant la propriété CSS `border-radius` pour les coins arrondis plutôt que des images de fond GIF.
- Certains gabarits de l’interface d’administration ont maintenant les classes `app-<app_name>` and `model-<model_name>` dans leur balise `<body>` pour permettre la personnalisation de la CSS par application ou par modèle.
- Les cellules de la liste d’objets pour modification de l’interface d’administration ont maintenant une classe `field-<field_name>` dans le code HTML pour permettre les personnalisations stylistiques.
- Les champs de recherche de l’interface d’administration peuvent désormais être personnalisés par requête grâce à la nouvelle méthode [`django.contrib.admin.ModelAdmin.get_search_fields()`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_search_fields).
- La méthode [`ModelAdmin.get_fields()`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields) peut être étendue pour personnaliser la valeur de [`ModelAdmin.fields`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields).
- En plus de la syntaxe `admin.site.register` existante, vous pouvez utiliser le nouveau décorateur [`register()`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.register) pour enregistrer un [`ModelAdmin`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin).
- Vous pouvez spécifier [`ModelAdmin.list_display_links`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display_links) `= None` pour désactiver les liens sur la grille de la page de liste des objets pour modification.
- Vous pouvez maintenant spécifier [`ModelAdmin.view_on_site`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.view_on_site) pour contrôler l’affichage ou non du lien « Voir sur le site ».
- Vous pouvez spécifier un ordre décroissant pour une valeur de [`ModelAdmin.list_display`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) en faisant précéder la valeur de `admin_order_field` avec un tiret.
- La méthode [`ModelAdmin.get_changeform_initial_data()`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_changeform_initial_data) peut être étendue pour définir un comportement personnalisé afin de configurer les données initiales du formulaire de modification.

#### [`django.contrib.auth`](/fr/3.1/topics/auth/#module-django.contrib.auth)

- Tous `**kwargs` passés à [`email_user()`](/fr/3.1/ref/contrib/auth/#django.contrib.auth.models.User.email_user) sont transmis lors de l’appel sous-jacent à [`send_mail()`](/fr/3.1/topics/email/#django.core.mail.send_mail).
- Le décorateur [`permission_required()`](/fr/3.1/topics/auth/default/#django.contrib.auth.decorators.permission_required) peut tout aussi bien prendre une liste d’autorisations qu’une seule autorisation.
- Vous pouvez étendre la nouvelle méthode [`AuthenticationForm.confirm_login_allowed()`](/fr/3.1/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed) afin de personnaliser plus facilement la politique d’ouverture de session.
- `django.contrib.auth.views.password_reset()` takes an optional
  `html_email_template_name` parameter used to send a multipart HTML email
  for password resets.
- The [`AbstractBaseUser.get_session_auth_hash()`](/fr/3.1/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash)
  method was added and if your [`AUTH_USER_MODEL`](/fr/3.1/ref/settings/#std-setting-AUTH_USER_MODEL) inherits from
  [`AbstractBaseUser`](/fr/3.1/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser), changing a user’s
  password now invalidates old sessions if the
  `django.contrib.auth.middleware.SessionAuthenticationMiddleware` is
  enabled. See [Invalidation de session lors du changement de mot de passe](/fr/3.1/topics/auth/default/#session-invalidation-on-password-change) for more details.

#### `django.contrib.formtools`

- Calls to `WizardView.done()` now include a `form_dict` to allow easier
  access to forms by their step name.

#### [`django.contrib.gis`](/fr/3.1/ref/contrib/gis/#module-django.contrib.gis)

- La version de la bibliothèque OpenLayers par défaut inclus dans les composants a été mise à jour, passant de la 2.11 à 2.13.
- Les géométries préparées supportent maintenant les prédicats `crosses`, `disjoint`, `overlaps`, `touches` et `within`, si GEOS 3.3 ou ultérieur est installé.

#### [`django.contrib.messages`](/fr/3.1/ref/contrib/messages/#module-django.contrib.messages)

- Les moteurs de [`django.contrib.messages`](/fr/3.1/ref/contrib/messages/#module-django.contrib.messages) qui utilisent des cookies respectent maintenant  les réglages [`SESSION_COOKIE_SECURE`](/fr/3.1/ref/settings/#std-setting-SESSION_COOKIE_SECURE) et [`SESSION_COOKIE_HTTPONLY`](/fr/3.1/ref/settings/#std-setting-SESSION_COOKIE_HTTPONLY).
- Le [processeur de contexte des messages](/fr/3.1/ref/contrib/messages/#message-displaying) ajoute maintenant un dictionnaire des niveaux par défaut sous le nom de `DEFAULT_MESSAGE_LEVELS`.
- Les objets [`Message`](/fr/3.1/ref/contrib/messages/#django.contrib.messages.storage.base.Message) ont maintenant un attribut `level_tag` qui contient la représentation textuelle du niveau de message.

#### [`django.contrib.redirects`](/fr/3.1/ref/contrib/redirects/#module-django.contrib.redirects)

- [`RedirectFallbackMiddleware`](/fr/3.1/ref/contrib/redirects/#django.contrib.redirects.middleware.RedirectFallbackMiddleware) a deux nouveaux attributs ([`response_gone_class`](/fr/3.1/ref/contrib/redirects/#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_gone_class) et [`response_redirect_class`](/fr/3.1/ref/contrib/redirects/#django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class)) qui spécifient les types d’instances [`HttpResponse`](/fr/3.1/ref/request-response/#django.http.HttpResponse) retournées par le middleware.

#### [`django.contrib.sessions`](/fr/3.1/topics/http/sessions/#module-django.contrib.sessions)

- The `"django.contrib.sessions.backends.cached_db"` session backend now
  respects [`SESSION_CACHE_ALIAS`](/fr/3.1/ref/settings/#std-setting-SESSION_CACHE_ALIAS). In previous versions, it always used
  the `default` cache.

#### [`django.contrib.sitemaps`](/fr/3.1/ref/contrib/sitemaps/#module-django.contrib.sitemaps)

- L”[`infrastructure de plan du site`](/fr/3.1/ref/contrib/sitemaps/#module-django.contrib.sitemaps) utilise maintenant [`lastmod`](/fr/3.1/ref/contrib/sitemaps/#django.contrib.sitemaps.Sitemap.lastmod) pour définir un en-tête `Last-Modified` dans la réponse. Cela permet au [`ConditionalGetMiddleware`](/fr/3.1/ref/middleware/#django.middleware.http.ConditionalGetMiddleware) de gérer des requêtes `GET` conditionnelles pour les plans de site qui définissent `lastmod`.

#### [`django.contrib.sites`](/fr/3.1/ref/contrib/sites/#module-django.contrib.sites)

- Le nouveau [`django.contrib.sites.middleware.CurrentSiteMiddleware`](/fr/3.1/ref/middleware/#django.contrib.sites.middleware.CurrentSiteMiddleware) permet de définir le site courant pour chaque requête.

#### [`django.contrib.staticfiles`](/fr/3.1/ref/contrib/staticfiles/#module-django.contrib.staticfiles)

- Les [classes de stockage de fichiers statiques](/fr/3.1/ref/contrib/staticfiles/#staticfiles-storages) peuvent être sous-classées pour remplacer les autorisations que les fichiers statiques et répertoires collectés reçoivent en réglant les paramètres [`file_permissions_mode`](/fr/3.1/ref/files/storage/#django.core.files.storage.FileSystemStorage.file_permissions_mode) et [`directory_permissions_mode`](/fr/3.1/ref/files/storage/#django.core.files.storage.FileSystemStorage.directory_permissions_mode) . Voir [`collectstatic`](/fr/3.1/ref/contrib/staticfiles/#django-admin-collectstatic) pour un exemple d’utilisation.
- The `CachedStaticFilesStorage` backend gets a sibling class called
  [`ManifestStaticFilesStorage`](/fr/3.1/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage)
  that doesn’t use the cache system at all but instead a JSON file called
  `staticfiles.json` for storing the mapping between the original file name
  (e.g. `css/styles.css`) and the hashed file name (e.g.
  `css/styles.55e7cbb9ba48.css`). The `staticfiles.json` file is created
  when running the [`collectstatic`](/fr/3.1/ref/contrib/staticfiles/#django-admin-collectstatic) management command and should
  be a less expensive alternative for remote storages such as Amazon S3.

  Voir la documentation de [`ManifestStaticFilesStorage`](/fr/3.1/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage) pour plus d’informations.
- [`findstatic`](/fr/3.1/ref/contrib/staticfiles/#django-admin-findstatic) accepte maintenant une verbosité de niveau 2, ce qui signifie qu’elle affichera les chemins relatifs des répertoires qu’elle a recherché. Voir [`findstatic`](/fr/3.1/ref/contrib/staticfiles/#django-admin-findstatic) par un exemple de sortie.

#### [`django.contrib.syndication`](/fr/3.1/ref/contrib/syndication/#module-django.contrib.syndication)

- L’élément `updated` du flux de syndication [`Atom1Feed`](/fr/3.1/ref/utils/#django.utils.feedgenerator.Atom1Feed) utilise maintenant `updateddate` au lieu de `pubdate`, permettant à l’élément `published` d’être inclut dans le flux (qui repose sur `pubdate`).

#### Cache

- Access to caches configured in [`CACHES`](/fr/3.1/ref/settings/#std-setting-CACHES) is now available via
  [`django.core.cache.caches`](/fr/3.1/topics/cache/#django.core.cache.caches). This dict-like object provides a different
  instance per thread. It supersedes `django.core.cache.get_cache()` which
  is now deprecated.
- Si vous instanciez un moteur de cache directement, soyez conscients qu’ils ne sont plus thread-safe, puisque [`django.core.cache.caches`](/fr/3.1/topics/cache/#django.core.cache.caches) génère maintenant différentes instances par thread.
- Définir l’argument [`TIMEOUT`](/fr/3.1/ref/settings/#std-setting-CACHES-TIMEOUT) du réglage [`CACHES`](/fr/3.1/ref/settings/#std-setting-CACHES) à `None` définiera les clés du cache comme « n’expirant pas » par défaut. Auparavant, il était seulement possible de passer `timeout = None` à la méthode `set()` des moteurs de cache.

#### Cross Site Request Forgery

- Le réglage [`CSRF_COOKIE_AGE`](/fr/3.1/ref/settings/#std-setting-CSRF_COOKIE_AGE) facilite l’utilisation des cookies de session CSRF.

#### Email

- [`send_mail()`](/fr/3.1/topics/email/#django.core.mail.send_mail) now accepts an `html_message`
  parameter for sending a multipart `text/plain` and
  `text/html` email.
- The SMTP [`EmailBackend`](/fr/3.1/topics/email/#django.core.mail.backends.smtp.EmailBackend) now accepts a
  `timeout` parameter.

#### Stockage de fichier

- Le verrouillage de fichier sur Windows dépendait précédemment du paquet PyWin32; s’il n’était pas été installé, le verrouillage de fichier échouait en silence. Cette dépendance a été supprimée, et le verrouillage de fichier est désormais implémenté nativement à la fois sur Windows et Unix.

#### Téléversement de fichiers

- Le nouvel attribut [`UploadedFile.content_type_extra`](/fr/3.1/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.content_type_extra) contient les paramètres supplémentaires passés à l’en-tête `content-type` lors d’un téléversement de fichier.
- Le nouveau réglage [`FILE_UPLOAD_DIRECTORY_PERMISSIONS`](/fr/3.1/ref/settings/#std-setting-FILE_UPLOAD_DIRECTORY_PERMISSIONS) contrôle les autorisations du système de fichiers pour les répertoires créés lors de téléversements de fichiers, tout comme [`FILE_UPLOAD_PERMISSIONS`](/fr/3.1/ref/settings/#std-setting-FILE_UPLOAD_PERMISSIONS) le fait pour les fichiers.
- L’attribut [`FileField.upload_to`](/fr/3.1/ref/models/fields/#django.db.models.FileField.upload_to) est maintenant facultatif. S’il est omis ou définie à `None` ou une chaîne vide, un sous-répertoire ne sera pas utilisé pour stocker les fichiers téléversés.
- Les fichiers téléversés sont désormais explicitement fermés avant que la réponse soit livrée au client. Les fichiers partiellement téléversés sont également fermés tant qu’ils sont nommés `file` dans le gestionnaire de téléversement.
- [`Storage.get_available_name()`](/fr/3.1/ref/files/storage/#django.core.files.storage.Storage.get_available_name) ajoute maintenant un trait de soulignement en plus d’une chaîne alphanumérique de 7 caractères aléatoire (e.g. `"_x3a1gho"`), plutôt que d’itérer sur un trait de soulignement suivi d’un nombre (e.g. `"_1"`, `"_2"`, etc.) pour éviter une attaque par déni de service. Ce changement a également été effectué dans les versions de sécurité 1.6.6, 1.5.9 et 1.4.14.

#### Formulaires

- Les balises `<label>` et `<input>` rendues par [`RadioSelect`](/fr/3.1/ref/forms/widgets/#django.forms.RadioSelect) et [`CheckboxSelectMultiple`](/fr/3.1/ref/forms/widgets/#django.forms.CheckboxSelectMultiple) lors de l’itération sur les boutons radio ou les cases à cocher incluent maintenant les attributs `for` et `id`, respectivement. Chaque bouton radio ou case à cocher inclut un attribut `id_for_label` produisant l’ID de l’élément.
- Les balises `<textarea>` rendues par [`Textarea`](/fr/3.1/ref/forms/widgets/#django.forms.Textarea) incluent maintenant un attribut `maxlength` si le champ de modèle [`TextField`](/fr/3.1/ref/models/fields/#django.db.models.TextField) possède un `max_length`.
- [`Field.choices`](/fr/3.1/ref/models/fields/#django.db.models.Field.choices) permet désormais de personnaliser l’étiquette « empty choice » en incluant un tuple avec une chaîne vide ou `None` pour la clé et l’étiquette personnalisée en tant que valeur. L’option vide par défaut `"----------"` sera omise dans ce cas.
- [`MultiValueField`](/fr/3.1/ref/forms/fields/#django.forms.MultiValueField) autorisent les sous-champs facultatifs en réglant l’argument `require_all_fields` à `False`. L’attribut `required` pour chaque champ individuel sera respecté, et une nouvelle erreur de validation `incomplete` sera déclenchée lorsqu’un champ requis est vide.
- La méthode [`clean()`](/fr/3.1/ref/forms/api/#django.forms.Form.clean) d’un formulaire n’a plus besoin de retourner `self.cleaned_data`. Si elle retourne un dictionnaire modifié alors il sera utilisé.
- Après une régression temporaire dans Django 1.6, il est maintenant de nouveau possible de faire en sorte que la méthode `coerce` de [`TypedChoiceField`](/fr/3.1/ref/forms/fields/#django.forms.TypedChoiceField) retourne une valeur arbitraire.
- [`SelectDateWidget.months`](/fr/3.1/ref/forms/widgets/#django.forms.SelectDateWidget.months) can be used to
  customize the wording of the months displayed in the select widget.
- Les paramètres `min_num` et `validate_min` ont été ajoutées à [`formset_factory()`](/fr/3.1/ref/forms/formsets/#django.forms.formsets.formset_factory) pour permettre la validation d’un nombre minimum de formulaires soumis.
- Les métaclasses utilisées par `Form` et `ModelForm` ont été retravaillées pour gérer plusieurs scénarios d’héritage. La limitation précédente qui empêchait d’hériter simultanément de deux `Form` et `ModelForm` a été supprimée tant que `ModelForm` apparaît en premier dans la MRO.
- Il est maintenant possible de supprimer un champ d’un `Form` lors d’un sous-classement en définissant son nom à `None`.
- Il est maintenant possible de personnaliser les messages d’erreur pour les contraintes  `unique`, `unique_for_date`, et `unique_together` de `ModelForm`. Afin de supporter `unique_together` ou tout autre `NON_FIELD_ERROR`, `ModelForm` regarde maintenant la clé `NON_FIELD_ERROR` dans le dictionnaire `error_messages` de la classe `Meta` interne à `ModelForm`. Voir les [considérations concernant le error\_messages du modèle](/fr/3.1/topics/forms/modelforms/#considerations-regarding-model-errormessages) pour plus de détails.

#### Internationalisation

- L’attribut [`django.middleware.locale.LocaleMiddleware.response_redirect_class`](/fr/3.1/ref/middleware/#django.middleware.locale.LocaleMiddleware.response_redirect_class) vous permet de personnaliser les redirections émises par le middleware.
- Le [`LocaleMiddleware`](/fr/3.1/ref/middleware/#django.middleware.locale.LocaleMiddleware) stocke désormais la langue choisie par l’utilisateur avec la clé de session `_language`. Elle ne devrait être uniquement accessible qu’à l’aide de la constante [`LANGUAGE_SESSION_KEY`](/fr/3.1/ref/utils/#django.utils.translation.LANGUAGE_SESSION_KEY). Auparavant, elle était stockée avec la clé `django_language` et la constante `LANGUAGE_SESSION_KEY` n’existait pas, mais les clés réservées par Django doivent commencer par un trait de soulignement. Par souci de rétro-compatibilité, `django_language` est toujours lue dans la 1.7. Les sessions seront migrés vers la nouvelle clé au fur et à mesure de leur écriture.
- La balise [`blocktrans`](/fr/3.1/topics/i18n/translation/#std-templatetag-blocktrans) supporte maintenant une option `trimmed`. Cette option supprimera les caractères de nouvelle ligne au début et à la fin du contenu de la balise `{%blocktrans%}`, remplacera les espaces blancs au début et à la fin d’une ligne et fusionnera toutes les lignes en une seule via l’utilisation d’un espace pour les séparer. Ceci est très utile pour l’indentation du contenu d’une balise `{% blocktrans%}` sans avoir les caractères d’indentation qui se retrouvent dans l’entrée correspondante du fichier PO, rendant le processus de traduction plus facile.
- Lorsque vous exécutez [`makemessages`](/fr/3.1/ref/django-admin/#django-admin-makemessages) à partir du répertoire racine de votre projet, toutes les chaînes extraites seront maintenant distribuées automatiquement au fichier de message de l’application ou du projet. Voir [Régionalisation : comment créer les fichiers de langues](/fr/3.1/topics/i18n/translation/#how-to-create-language-files)  pour plus de détails.
- La commande [`makemessages`](/fr/3.1/ref/django-admin/#django-admin-makemessages) ajoute maintenant toujours le drapeau de ligne de commande `--previous` à la commande `msgmerge`, gardant les chaînes déjà traduites dans les fichiers po pour les chaînes floues.
- Les paramètres suivants ont été introduits pour régler les options du cookie de langue : [`LANGUAGE_COOKIE_AGE`](/fr/3.1/ref/settings/#std-setting-LANGUAGE_COOKIE_AGE), [`LANGUAGE_COOKIE_DOMAIN`](/fr/3.1/ref/settings/#std-setting-LANGUAGE_COOKIE_DOMAIN) et [`LANGUAGE_COOKIE_PATH`](/fr/3.1/ref/settings/#std-setting-LANGUAGE_COOKIE_PATH).
- Added [Régionalisation des formats](/fr/3.1/topics/i18n/formatting/) for Esperanto.

#### Commandes d’administration

- The new [`--no-color`](/fr/3.1/ref/django-admin/#cmdoption-no-color) option for `django-admin` disables the
  colorization of management command output.
- The new [`dumpdata --natural-foreign`](/fr/3.1/ref/django-admin/#cmdoption-dumpdata-natural-foreign) and [`dumpdata
  --natural-primary`](/fr/3.1/ref/django-admin/#cmdoption-dumpdata-natural-primary) options, and the new `use_natural_foreign_keys` and
  `use_natural_primary_keys` arguments for `serializers.serialize()`, allow
  the use of natural primary keys when serializing.
- It is no longer necessary to provide the cache table name or the
  `--database` option for the [`createcachetable`](/fr/3.1/ref/django-admin/#django-admin-createcachetable) command.
  Django takes this information from your settings file. If you have configured
  multiple caches or multiple databases, all cache tables are created.
- La commande [`runserver`](/fr/3.1/ref/django-admin/#django-admin-runserver) a reçu plusieurs améliorations :

  - Sur les systèmes Linux, si [pyinotify](https://pypi.org/project/pyinotify/) est installé, le serveur de développement se rechargera immédiatement lorsqu’un fichier est modifié. Auparavant, il interrogeait le système de fichiers sur les changements, toutes les secondes. Cela causait un léger retard avant le rechargement et réduisait la vie de la batterie sur les ordinateurs portables.
  - En outre, le serveur de développement se recharge automatiquement lorsqu’un fichier de traduction est mis à jour, i.e. après l’exécution de [`compilemessages`](/fr/3.1/ref/django-admin/#django-admin-compilemessages).
  - Toutes les requêtes HTTP sont enregistrées dans la console, y compris les requêtes de fichiers statiques ou celles du `favicon.ico` qui étaient habituellement filtrées.
- Les commandes de gestion peuvent maintenant produire une syntaxe de sortie colorisée sous Windows, si l’outil tiers ANSICON est installé et actif.
- La commande [`collectstatic`](/fr/3.1/ref/contrib/staticfiles/#django-admin-collectstatic) prend désormais en charge l’option de lien symbolique sur Windows NT 6 (Windows Vista et plus récent).
- Initial SQL data now works better if the [sqlparse](https://pypi.org/project/sqlparse/) Python library is
  installed.

  Notez que cette pratique est déconseillée en faveur de l’opération [`RunSQL`](/fr/3.1/ref/migration-operations/#django.db.migrations.operations.RunSQL) des migrations, qui bénéficie du comportement amélioré.

#### Modèles

- La méthode [`QuerySet.update_or_create()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.update_or_create) a été ajoutée.
- La nouvelle option `Meta` de modèle [`default_permissions`](/fr/3.1/ref/models/options/#django.db.models.Options.default_permissions) vous permet de personnaliser (ou de désactiver) la création des autorisations d’ajout, modification et suppression, par défaut.
- Les [`OneToOneField`](/fr/3.1/ref/models/fields/#django.db.models.OneToOneField) explicites pour l”[Héritage multi-table](/fr/3.1/topics/db/models/#multi-table-inheritance) sont maintenant découverts dans les classes abstraites.
- It is now possible to avoid creating a backward relation for
  [`OneToOneField`](/fr/3.1/ref/models/fields/#django.db.models.OneToOneField) by setting its
  [`related_name`](/fr/3.1/ref/models/fields/#django.db.models.ForeignKey.related_name) to
  `'+'` or ending it with `'+'`.
- Les [`expressions F`](/fr/3.1/ref/models/expressions/#django.db.models.F) supporte l’opérateur puissance (`**`).
- Les méthodes `remove()` et `clean()` des gestionnaires connexes créés par `ForeignKey` et `GenericForeignKey` acceptent maintenant l’argument mot-clef `bulk` pour contrôler l’utilisation ou non des opérations en vrac (i.e. en utilisant `QuerySet.update()`). Par défaut, `True`.
- Il est maintenant possible d’utiliser `None` comme valeur de requête pour la recherche [`iexact`](/fr/3.1/ref/models/querysets/#std-fieldlookup-iexact).
- Il est maintenant possible de passer un appelable comme valeur de l’attribut [`limit_choices_to`](/fr/3.1/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) lors de la définition d’un `ForeignKey` ou d’un `ManyToManyField`.
- L’appel à [`only()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.only) et [`defer()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.defer) sur le résultat de [`QuerySet.values()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.values) lève maintenant une erreur (avant cela, il résultait soit en une erreur de base de données ou des données incorrectes).
- Vous pouvez utiliser une seule liste pour [`index_together`](/fr/3.1/ref/models/options/#django.db.models.Options.index_together) (plutôt qu’une liste de listes) lors de la spécification d’un seul ensemble de champs.
- Les modèles personnalisés intermédiaires ayant plus d’une clé étrangère vers l’un des modèles participant à une relation multiple sont maintenant autorisés, à condition que vous spécifiez explicitement quelles clés étrangères doivent être utilisées en configurant le nouvel argument [`ManyToManyField.through_fields`](/fr/3.1/ref/models/fields/#django.db.models.ManyToManyField.through_fields).
- L””assignation d’une instance de modèle à un champ non-relationnel lèvera maintenant une erreur. Auparavant, cela fonctionnait si le champ jouant le rôle de clé primaire acceptait les entiers en entrée.
- Les champs d’entiers sont maintenant validés avec les valeurs max et min spécifiques au moteur de base de données en fonction de leur [`internal_type`](/fr/3.1/ref/models/fields/#django.db.models.Field.get_internal_type). Auparavant, la validation de champ de modèle n’empêchait pas les valeurs qui sortait de leur gamme de valeurs, relatives au type de colonne, d’être enregistrées; résultant alors en une erreur d’intégrité.
- Il est maintenant possible d’utiliser [`order_by()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.order_by) de façon explicite avec un champ de relation `_id` en utilisant son nom d’attribut.

#### Signaux

- L’argument `enter` a été ajouté au signal [`setting_changed`](/fr/3.1/ref/signals/#django.test.signals.setting_changed).
- Les signaux de modèle peuvent maintenant être connectés à l’aide d’un `str` au format `'app_label.ModelName'` – tout comme les champs connexes – pour référencer de manière paresseuse leurs émetteurs.

#### Gabarits

- La méthode [`Context.push()`](/fr/3.1/ref/templates/api/#django.template.Context.push) retourne maintenant un gestionnaire de contexte qui appelle automatiquement [`pop()`](/fr/3.1/ref/templates/api/#django.template.Context.pop) à la sortie de la déclaration `with`. En outre, [`push()`](/fr/3.1/ref/templates/api/#django.template.Context.push) accepte désormais des paramètres qui sont passés au `dict` du constructeur qui est utilisé pour construire le nouveau niveau de contexte.
- La nouvelle méthode [`Context.flatten()`](/fr/3.1/ref/templates/api/#django.template.Context.flatten) retourne une pile de `Context` sous la forme d’un dictionnaire unique à plat.
- Les objets `Context` peuvent désormais être comparés pour l’égalité (en interne, cela utilise [`Context.flatten()`](/fr/3.1/ref/templates/api/#django.template.Context.flatten) de sorte que la structure interne de chaque pile de `Context` n’a pas d’importance tant que leur version aplatie est identique).
- La balise de gabarit [`widthratio`](/fr/3.1/ref/templates/builtins/#std-templatetag-widthratio) accepte maintenant un paramère `"as"` pour capturer le résultat dans une variable.
- La balise de gabarit [`include`](/fr/3.1/ref/templates/builtins/#std-templatetag-include) acceptera aussi désormais toute chose avec une méthode `render()` (comme un `Template`) comme argument. Les arguments sous forme de chaînes seront, comme toujours, recherchés à l’aide de [`get_template()`](/fr/3.1/topics/templates/#django.template.loader.get_template).
- Il est maintenant possible d’inclure les gabarits récursivement avec [`include`](/fr/3.1/ref/templates/builtins/#std-templatetag-include).
- Template objects now have an origin attribute set when
  `TEMPLATE_DEBUG` is `True`. This allows template origins to be
  inspected and logged outside of the `django.template` infrastructure.
- Les exceptions `TypeError` ne sont plus réduites au silence lorsqu’elles sont levées au cours du rendu d’un gabarit.
- The following functions now accept a `dirs` parameter which is a list or
  tuple to override `TEMPLATE_DIRS`:

  - [`django.template.loader.get_template()`](/fr/3.1/topics/templates/#django.template.loader.get_template)
  - [`django.template.loader.select_template()`](/fr/3.1/topics/templates/#django.template.loader.select_template)
  - [`django.shortcuts.render()`](/fr/3.1/topics/http/shortcuts/#django.shortcuts.render)
  - `django.shortcuts.render_to_response()`
- The [`time`](/fr/3.1/ref/templates/builtins/#std-templatefilter-time) filter now accepts timezone-related [format
  specifiers](/fr/3.1/ref/templates/builtins/#date-and-time-formatting-specifiers) `'e'`, `'O'` , `'T'`
  and `'Z'` and is able to digest [time-zone-aware](/fr/3.1/topics/i18n/timezones/#naive-vs-aware-datetimes) `datetime` instances performing the expected
  rendering.
- The [`cache`](/fr/3.1/topics/cache/#std-templatetag-cache) tag will now try to use the cache called
  « template\_fragments » if it exists and fall back to using the default cache
  otherwise. It also now accepts an optional `using` keyword argument to
  control which cache it uses.
- The new [`truncatechars_html`](/fr/3.1/ref/templates/builtins/#std-templatefilter-truncatechars_html) filter truncates a string to be no
  longer than the specified number of characters, taking HTML into account.

#### Requêtes et réponses

- The new [`HttpRequest.scheme`](/fr/3.1/ref/request-response/#django.http.HttpRequest.scheme) attribute
  specifies the scheme of the request (`http` or `https` normally).
- The shortcut [`redirect()`](/fr/3.1/topics/http/shortcuts/#django.shortcuts.redirect) now supports
  relative URLs.
- The new [`JsonResponse`](/fr/3.1/ref/request-response/#django.http.JsonResponse) subclass of
  [`HttpResponse`](/fr/3.1/ref/request-response/#django.http.HttpResponse) helps easily create JSON-encoded responses.

#### Tests

- [`DiscoverRunner`](/fr/3.1/topics/testing/advanced/#django.test.runner.DiscoverRunner) has two new attributes,
  [`test_suite`](/fr/3.1/topics/testing/advanced/#django.test.runner.DiscoverRunner.test_suite) and
  [`test_runner`](/fr/3.1/topics/testing/advanced/#django.test.runner.DiscoverRunner.test_runner), which facilitate
  overriding the way tests are collected and run.
- The `fetch_redirect_response` argument was added to
  [`assertRedirects()`](/fr/3.1/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects). Since the test
  client can’t fetch externals URLs, this allows you to use `assertRedirects`
  with redirects that aren’t part of your Django app.
- Correct handling of scheme when making comparisons in
  [`assertRedirects()`](/fr/3.1/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects).
- The `secure` argument was added to all the request methods of
  [`Client`](/fr/3.1/topics/testing/tools/#django.test.Client). If `True`, the request will be made
  through HTTPS.
- [`assertNumQueries()`](/fr/3.1/topics/testing/tools/#django.test.TransactionTestCase.assertNumQueries) now prints
  out the list of executed queries if the assertion fails.
- The `WSGIRequest` instance generated by the test handler is now attached to
  the [`django.test.Response.wsgi_request`](/fr/3.1/topics/testing/tools/#django.test.Response.wsgi_request) attribute.
- The database settings for testing have been collected into a dictionary
  named [`TEST`](/fr/3.1/ref/settings/#std-setting-DATABASE-TEST).

#### Utilitaires

- Amélioration de l’exactitude de [`strip_tags()`](/fr/3.1/ref/utils/#django.utils.html.strip_tags) (mais elle ne peut toujours pas garantir un résultat HTML sécurisé, comme indiqué dans la documentation).

#### Validateurs

- [`RegexValidator`](/fr/3.1/ref/validators/#django.core.validators.RegexValidator) now accepts the optional
  [`flags`](/fr/3.1/ref/validators/#django.core.validators.RegexValidator.flags) and
  Boolean [`inverse_match`](/fr/3.1/ref/validators/#django.core.validators.RegexValidator.inverse_match) arguments.
  The [`inverse_match`](/fr/3.1/ref/validators/#django.core.validators.RegexValidator.inverse_match) attribute
  determines if the [`ValidationError`](/fr/3.1/ref/exceptions/#django.core.exceptions.ValidationError) should
  be raised when the regular expression pattern matches (`True`) or does not
  match (`False`, by default) the provided `value`. The
  [`flags`](/fr/3.1/ref/validators/#django.core.validators.RegexValidator.flags) attribute sets the flags
  used when compiling a regular expression string.
- [`URLValidator`](/fr/3.1/ref/validators/#django.core.validators.URLValidator) now accepts an optional
  `schemes` argument which allows customization of the accepted URI schemes
  (instead of the defaults `http(s)` and `ftp(s)`).
- [`validate_email()`](/fr/3.1/ref/validators/#django.core.validators.validate_email) now accepts addresses with
  IPv6 literals, like `example@[2001:db8::1]`, as specified in RFC 5321.

## Backwards incompatible changes in 1.7

> **Warning**
>
> In addition to the changes outlined in this section, be sure to review the
> [deprecation plan](/fr/3.1/internals/deprecation/#deprecation-removed-in-1-7) for any features that
> have been removed. If you haven’t updated your code within the
> deprecation timeline for a given feature, its removal may appear as a
> backwards incompatible change.

### `allow_syncdb` / `allow_migrate`

While Django will still look at `allow_syncdb` methods even though they
should be renamed to `allow_migrate`, there is a subtle difference in which
models get passed to these methods.

For apps with migrations, `allow_migrate` will now get passed
[historical models](/fr/3.1/topics/migrations/#historical-models), which are special versioned models
without custom attributes, methods or managers. Make sure your `allow_migrate`
methods are only referring to fields or other items in `model._meta`.

### initial\_data

Apps with migrations will not load `initial_data` fixtures when they have
finished migrating. Apps without migrations will continue to load these fixtures
during the phase of `migrate` which emulates the old `syncdb` behavior,
but any new apps will not have this support.

Instead, you are encouraged to load initial data in migrations if you need it
(using the `RunPython` operation and your model classes);
this has the added advantage that your initial data will not need updating
every time you change the schema.

Additionally, like the rest of Django’s old `syncdb` code, `initial_data`
has been started down the deprecation path and will be removed in Django 1.9.

### deconstruct() and serializability

Django now requires all Field classes and all of their constructor arguments
to be serializable. If you modify the constructor signature in your custom
Field in any way, you’ll need to implement a deconstruct() method;
we’ve expanded the custom field documentation with [instructions
on implementing this method](/fr/3.1/howto/custom-model-fields/#custom-field-deconstruct-method).

The requirement for all field arguments to be
[serializable](/fr/3.1/topics/migrations/#migration-serializing) means that any custom class
instances being passed into Field constructors - things like custom Storage
subclasses, for instance - need to have a [deconstruct method defined on
them as well](/fr/3.1/topics/migrations/#custom-deconstruct-method), though Django provides a handy
class decorator that will work for most applications.

### App-loading changes

#### Start-up sequence

Django 1.7 loads application configurations and models as soon as it starts.
While this behavior is more straightforward and is believed to be more robust,
regressions cannot be ruled out. See [Dépannage](/fr/3.1/ref/applications/#applications-troubleshooting) for
solutions to some problems you may encounter.

#### Scripts autonomes

If you’re using Django in a plain Python script — rather than a management
command — and you rely on the [`DJANGO_SETTINGS_MODULE`](/fr/3.1/topics/settings/#envvar-DJANGO_SETTINGS_MODULE) environment
variable, you must now explicitly initialize Django at the beginning of your
script with:

```
>>> import django
>>> django.setup()
```

Otherwise, you will hit an `AppRegistryNotReady` exception.

#### Les scripts WSGI

Until Django 1.3, the recommended way to create a WSGI application was:

```
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
```

In Django 1.4, support for WSGI was improved and the API changed to:

```
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
```

If you’re still using the former style in your WSGI script, you need to
upgrade to the latter, or you will hit an `AppRegistryNotReady` exception.

#### App registry consistency

It is no longer possible to have multiple installed applications with the same
label. In previous versions of Django, this didn’t always work correctly, but
didn’t crash outright either.

If you have two apps with the same label, you should create an
[`AppConfig`](/fr/3.1/ref/applications/#django.apps.AppConfig) for one of them and override its
[`label`](/fr/3.1/ref/applications/#django.apps.AppConfig.label) there. You should then adjust your code
wherever it references this application or its models with the old label.

It isn’t possible to import the same model twice through different paths any
more. As of Django 1.6, this may happen only if you’re manually putting a
directory and a subdirectory on [`PYTHONPATH`](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH). Refer to the section on
the new project layout in the [1.4 release notes](/fr/3.1/releases/1.4/) for
migration instructions.

Vous devez vous assurez de :

- All models are defined in applications that are listed in
  [`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS) or have an explicit
  [`app_label`](/fr/3.1/ref/models/options/#django.db.models.Options.app_label).
- Models aren’t imported as a side-effect of loading their application.
  Specifically, you shouldn’t import models in the root module of an
  application nor in the module that define its configuration class.

Django will enforce these requirements as of version 1.9, after a deprecation
period.

#### Subclassing AppCommand

Subclasses of [`AppCommand`](/fr/3.1/howto/custom-management-commands/#django.core.management.AppCommand) must now implement a
[`handle_app_config()`](/fr/3.1/howto/custom-management-commands/#django.core.management.AppCommand.handle_app_config) method instead of
`handle_app()`. This method receives an [`AppConfig`](/fr/3.1/ref/applications/#django.apps.AppConfig)
instance instead of a models module.

#### Introspecting applications

Since [`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS) now supports application configuration classes
in addition to application modules, you should review code that accesses this
setting directly and use the app registry ([`django.apps.apps`](/fr/3.1/ref/applications/#django.apps.apps)) instead.

The app registry has preserved some features of the old app cache. Even though
the app cache was a private API, obsolete methods and arguments will be
removed through a standard deprecation path, with the exception of the
following changes that take effect immediately:

- `get_model` raises [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) instead of returning `None` when no
  model is found.
- The `only_installed` argument of `get_model` and `get_models` no
  longer exists, nor does the `seed_cache` argument of `get_model`.

### Management commands and order of [`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS)

When several applications provide management commands with the same name,
Django loads the command from the application that comes first in
[`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS). Previous versions loaded the command from the
application that came last.

This brings discovery of management commands in line with other parts of
Django that rely on the order of [`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS), such as static
files, templates, and translations.

### `ValidationError` constructor and internal storage

The behavior of the `ValidationError` constructor has changed when it
receives a container of errors as an argument (e.g. a `list` or an
`ErrorList`):

- It converts any strings it finds to instances of `ValidationError`
  before adding them to its internal storage.
- It doesn’t store the given container but rather copies its content to its
  own internal storage; previously the container itself was added to the
  `ValidationError` instance and used as internal storage.

This means that if you access the `ValidationError` internal storages, such
as `error_list`; `error_dict`; or the return value of
`update_error_dict()` you may find instances of `ValidationError` where you
would have previously found strings.

Also if you directly assigned the return value of `update_error_dict()`
to `Form._errors` you may inadvertently add `list` instances where
`ErrorList` instances are expected. This is a problem because unlike a
simple `list`, an `ErrorList` knows how to handle instances of
`ValidationError`.

Most use-cases that warranted using these private APIs are now covered by
the newly introduced [`Form.add_error()`](/fr/3.1/ref/forms/api/#django.forms.Form.add_error)
method:

```
# Old pattern:
try:
    # ...
except ValidationError as e:
    self._errors = e.update_error_dict(self._errors)

# New pattern:
try:
    # ...
except ValidationError as e:
    self.add_error(None, e)
```

If you need both Django \<= 1.6 and 1.7 compatibility you can’t use
[`Form.add_error()`](/fr/3.1/ref/forms/api/#django.forms.Form.add_error) since it
wasn’t available before Django 1.7, but you can use the following
workaround to convert any `list` into `ErrorList`:

```
try:
    # ...
except ValidationError as e:
    self._errors = e.update_error_dict(self._errors)

# Additional code to ensure ``ErrorDict`` is exclusively
# composed of ``ErrorList`` instances.
for field, error_list in self._errors.items():
    if not isinstance(error_list, self.error_class):
        self._errors[field] = self.error_class(error_list)
```

### Behavior of `LocMemCache` regarding pickle errors

An inconsistency existed in previous versions of Django regarding how pickle
errors are handled by different cache backends.
`django.core.cache.backends.locmem.LocMemCache` used to fail silently when
such an error occurs, which is inconsistent with other backends and leads to
cache-specific errors. This has been fixed in Django 1.7, see
[#21200](https://code.djangoproject.com/ticket/21200) for more details.

### Cache keys are now generated from the request’s absolute URL

Previous versions of Django generated cache keys using a request’s path and
query string but not the scheme or host. If a Django application was serving
multiple subdomains or domains, cache keys could collide. In Django 1.7, cache
keys vary by the absolute URL of the request including scheme, host, path, and
query string. For example, the URL portion of a cache key is now generated from
`https://www.example.com/path/to/?key=val` rather than `/path/to/?key=val`.
The cache keys generated by Django 1.7 will be different from the keys
generated by older versions of Django. After upgrading to Django 1.7, the first
request to any previously cached URL will be a cache miss.

### Passing `None` to `Manager.db_manager()`

In previous versions of Django, it was possible to use
`db_manager(using=None)` on a model manager instance to obtain a manager
instance using default routing behavior, overriding any manually specified
database routing. In Django 1.7, a value of `None` passed to db\_manager will
produce a router that *retains* any manually assigned database routing – the
manager will *not* be reset. This was necessary to resolve an inconsistency in
the way routing information cascaded over joins. See [#13724](https://code.djangoproject.com/ticket/13724) for more
details.

### pytz peut être requis

If your project handles datetimes before 1970 or after 2037 and Django raises
a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) when encountering them, you will have to install [pytz](https://pypi.org/project/pytz/). You
may be affected by this problem if you use Django’s time zone-related date
formats or [`django.contrib.syndication`](/fr/3.1/ref/contrib/syndication/#module-django.contrib.syndication).

### `remove()` and `clear()` methods of related managers

The `remove()` and `clear()` methods of the related managers created by
`ForeignKey`, `GenericForeignKey`, and `ManyToManyField` suffered from a
number of issues. Some operations ran multiple data modifying queries without
wrapping them in a transaction, and some operations didn’t respect default
filtering when it was present (i.e. when the default manager on the related
model implemented a custom `get_queryset()`).

Fixing the issues introduced some backward incompatible changes:

- The default implementation of `remove()` for `ForeignKey` related managers
  changed from a series of `Model.save()` calls to a single
  `QuerySet.update()` call. The change means that `pre_save` and
  `post_save` signals aren’t sent anymore. You can use the `bulk=False`
  keyword argument to revert to the previous behavior.
- The `remove()` and `clear()` methods for `GenericForeignKey` related
  managers now perform bulk delete. The `Model.delete()` method isn’t called
  on each instance anymore. You can use the `bulk=False` keyword argument to
  revert to the previous behavior.
- The `remove()` and `clear()` methods for `ManyToManyField` related
  managers perform nested queries when filtering is involved, which may or
  may not be an issue depending on your database and your data itself.
  See [this note](/fr/3.1/ref/models/querysets/#nested-queries-performance) for more details.

### Admin login redirection strategy

Historically, the Django admin site passed the request from an unauthorized or
unauthenticated user directly to the login view, without HTTP redirection. In
Django 1.7, this behavior changed to conform to a more traditional workflow
where any unauthorized request to an admin page will be redirected (by HTTP
status code 302) to the login page, with the `next` parameter set to the
referring path. The user will be redirected there after a successful login.

Note also that the admin login form has been updated to not contain the
`this_is_the_login_form` field (now unused) and the `ValidationError` code
has been set to the more regular `invalid_login` key.

### `select_for_update()` exige une transaction

Historiquement, les requêtes utilisant [`select_for_update()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_for_update) pouvaient être exécutées en mode autocommit, en dehors d’une transaction. Avant Django 1.6, le mode de transaction automatique de Django permettait cela afin de verrouiller les éléments jusqu’à l’opération d’écriture suivante. Django 1.6 introduit l’autocommit au niveau de la base de données; depuis lors, l’exécution dans un tel contexte annule l’effet de `select_for_update()`. Il est donc supposé maintenant être une erreur et lève une exception.

This change was made because such errors can be caused by including an
app which expects global transactions (e.g. [`ATOMIC_REQUESTS`](/fr/3.1/ref/settings/#std-setting-DATABASE-ATOMIC_REQUESTS) set to `True`), or Django’s old autocommit
behavior, in a project which runs without them; and further, such
errors may manifest as data-corruption bugs. It was also made in
Django 1.6.3.

Ce changement peut entraîner des échecs de test si vous utilisez `select_for_update()` dans une classe de test qui est une sous-classe de [`TransactionTestCase`](/fr/3.1/topics/testing/tools/#django.test.TransactionTestCase) au lieu de [`TestCase`](/fr/3.1/topics/testing/tools/#django.test.TestCase).

### Contrib middleware removed from default `MIDDLEWARE_CLASSES`

The [app-loading refactor](#app-loading-refactor-17-release-note)
deprecated using models from apps which are not part of the
[`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS) setting. This exposed an incompatibility between
the default [`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS) and `MIDDLEWARE_CLASSES` in the
global defaults (`django.conf.global_settings`). To bring these settings in
sync and prevent deprecation warnings when doing things like testing reusable
apps with minimal settings,
[`SessionMiddleware`](/fr/3.1/ref/middleware/#django.contrib.sessions.middleware.SessionMiddleware),
[`AuthenticationMiddleware`](/fr/3.1/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware), and
[`MessageMiddleware`](/fr/3.1/ref/middleware/#django.contrib.messages.middleware.MessageMiddleware) were removed
from the defaults. These classes will still be included in the default settings
generated by [`startproject`](/fr/3.1/ref/django-admin/#django-admin-startproject). Most projects will not be affected by
this change but if you were not previously declaring the
`MIDDLEWARE_CLASSES` in your project settings and relying on the
global default you should ensure that the new defaults are in line with your
project’s needs. You should also check for any code that accesses
`django.conf.global_settings.MIDDLEWARE_CLASSES` directly.

### Divers

- The [`django.core.files.uploadhandler.FileUploadHandler.new_file()`](/fr/3.1/ref/files/uploads/#django.core.files.uploadhandler.FileUploadHandler.new_file)
  method is now passed an additional `content_type_extra` parameter. If you
  have a custom [`FileUploadHandler`](/fr/3.1/ref/files/uploads/#django.core.files.uploadhandler.FileUploadHandler)
  that implements `new_file()`, be sure it accepts this new parameter.
- [`ModelFormSet`](/fr/3.1/topics/forms/modelforms/#django.forms.models.BaseModelFormSet)s no longer
  delete instances when `save(commit=False)` is called. See
  [`can_delete`](/fr/3.1/topics/forms/formsets/#django.forms.formsets.BaseFormSet.can_delete) for instructions on how
  to manually delete objects from deleted forms.
- Loading empty fixtures emits a `RuntimeWarning` rather than raising
  [`CommandError`](/fr/3.1/howto/custom-management-commands/#django.core.management.CommandError).
- [`django.contrib.staticfiles.views.serve()`](/fr/3.1/ref/contrib/staticfiles/#django.contrib.staticfiles.views.serve) will now raise an
  [`Http404`](/fr/3.1/topics/http/views/#django.http.Http404) exception instead of
  [`ImproperlyConfigured`](/fr/3.1/ref/exceptions/#django.core.exceptions.ImproperlyConfigured) when [`DEBUG`](/fr/3.1/ref/settings/#std-setting-DEBUG)
  is `False`. This change removes the need to conditionally add the view to
  your root URLconf, which in turn makes it safe to reverse by name. It also
  removes the ability for visitors to generate spurious HTTP 500 errors by
  requesting static files that don’t exist or haven’t been collected yet.
- The [`django.db.models.Model.__eq__()`](/fr/3.1/ref/models/instances/#django.db.models.Model.__eq__) method is now defined in a
  way where instances of a proxy model and its base model are considered
  equal when primary keys match. Previously only instances of exact same
  class were considered equal on primary key match.
- The [`django.db.models.Model.__eq__()`](/fr/3.1/ref/models/instances/#django.db.models.Model.__eq__) method has changed such that
  two `Model` instances without primary key values won’t be considered
  equal (unless they are the same instance).
- The [`django.db.models.Model.__hash__()`](/fr/3.1/ref/models/instances/#django.db.models.Model.__hash__) method will now raise `TypeError`
  when called on an instance without a primary key value. This is done to
  avoid mutable `__hash__` values in containers.
- [`AutoField`](/fr/3.1/ref/models/fields/#django.db.models.AutoField) columns in SQLite databases will now be
  created using the `AUTOINCREMENT` option, which guarantees monotonic
  increments. This will cause primary key numbering behavior to change on
  SQLite, becoming consistent with most other SQL databases. This will only
  apply to newly created tables. If you have a database created with an older
  version of Django, you will need to migrate it to take advantage of this
  feature. For example, you could do the following:

  1. Use [`dumpdata`](/fr/3.1/ref/django-admin/#django-admin-dumpdata) to save your data.
  2. Rename the existing database file (keep it as a backup).
  3. Run [`migrate`](/fr/3.1/ref/django-admin/#django-admin-migrate) to create the updated schema.
  4. Use [`loaddata`](/fr/3.1/ref/django-admin/#django-admin-loaddata) to import the fixtures you exported in (1).
- `django.contrib.auth.models.AbstractUser` no longer defines a
  [`get_absolute_url()`](/fr/3.1/ref/models/instances/#django.db.models.Model.get_absolute_url) method. The old definition
  returned  `"/users/%s/" % urlquote(self.username)` which was arbitrary
  since applications may or may not define such a url in `urlpatterns`.
  Define a `get_absolute_url()` method on your own custom user object or use
  [`ABSOLUTE_URL_OVERRIDES`](/fr/3.1/ref/settings/#std-setting-ABSOLUTE_URL_OVERRIDES) if you want a URL for your user.
- The static asset-serving functionality of the
  [`django.test.LiveServerTestCase`](/fr/3.1/topics/testing/tools/#django.test.LiveServerTestCase) class has been simplified: Now it’s
  only able to serve content already present in [`STATIC_ROOT`](/fr/3.1/ref/settings/#std-setting-STATIC_ROOT) when
  tests are run. The ability to transparently serve all the static assets
  (similarly to what one gets with [`DEBUG = True`](/fr/3.1/ref/settings/#std-setting-DEBUG) at
  development-time) has been moved to a new class that lives in the
  `staticfiles` application (the one actually in charge of such feature):
  [`django.contrib.staticfiles.testing.StaticLiveServerTestCase`](/fr/3.1/ref/contrib/staticfiles/#django.contrib.staticfiles.testing.StaticLiveServerTestCase). In other
  words, `LiveServerTestCase` itself is less powerful but at the same time
  has less magic.

  Rationale behind this is removal of dependency of non-contrib code on
  contrib applications.
- The old cache URI syntax (e.g. `"locmem://"`) is no longer supported. It
  still worked, even though it was not documented or officially supported. If
  you’re still using it, please update to the current [`CACHES`](/fr/3.1/ref/settings/#std-setting-CACHES) syntax.
- The default ordering of `Form` fields in case of inheritance has changed to
  follow normal Python MRO. Fields are now discovered by iterating through the
  MRO in reverse with the topmost class coming last. This only affects you if
  you relied on the default field ordering while having fields defined on both
  the current class *and* on a parent `Form`.
- The `required` argument of
  [`SelectDateWidget`](/fr/3.1/ref/forms/widgets/#django.forms.SelectDateWidget) has been removed.
  This widget now respects the form field’s `is_required` attribute like
  other widgets.
- `Widget.is_hidden` is now a read-only property, getting its value by
  introspecting the presence of `input_type == 'hidden'`.
- [`select_related()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related) now chains in the
  same way as other similar calls like `prefetch_related`. That is,
  `select_related('foo', 'bar')` is equivalent to
  `select_related('foo').select_related('bar')`. Previously the latter would
  have been equivalent to `select_related('bar')`.
- GeoDjango supprime le support pour GEOS \< 3.1.
- The `init_connection_state` method of database backends now executes in
  autocommit mode (unless you set [`AUTOCOMMIT`](/fr/3.1/ref/settings/#std-setting-DATABASE-AUTOCOMMIT)
  to `False`). If you maintain a custom database backend, you should check
  that method.
- The `django.db.backends.BaseDatabaseFeatures.allows_primary_key_0`
  attribute has been renamed to `allows_auto_pk_0` to better describe it.
  It’s `True` for all database backends included with Django except MySQL
  which does allow primary keys with value 0. It only forbids *autoincrement*
  primary keys with value 0.
- Shadowing model fields defined in a parent model has been forbidden as this
  creates ambiguity in the expected model behavior. In addition, clashing
  fields in the model inheritance hierarchy result in a system check error.
  For example, if you use multi-inheritance, you need to define custom primary
  key fields on parent models, otherwise the default `id` fields will clash.
  See [Héritage multiple](/fr/3.1/topics/db/models/#model-multiple-inheritance-topic) for details.
- `django.utils.translation.parse_accept_lang_header()` now returns
  lowercase locales, instead of the case as it was provided. As locales should
  be treated case-insensitive this allows us to speed up locale detection.
- `django.utils.translation.get_language_from_path()` and
  `django.utils.translation.trans_real.get_supported_language_variant()`
  now no longer have a `supported` argument.
- The `shortcut` view in `django.contrib.contenttypes.views` now supports
  protocol-relative URLs (e.g. `//example.com`).
- [`GenericRelation`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericRelation) now supports an
  optional `related_query_name` argument. Setting `related_query_name` adds
  a relation from the related object back to the content type for filtering,
  ordering and other query operations.
- When running tests on PostgreSQL, the [`USER`](/fr/3.1/ref/settings/#std-setting-USER) will need read access
  to the built-in `postgres` database. This is in lieu of the previous
  behavior of connecting to the actual non-test database.
- As part of the [System check framework](/fr/3.1/ref/checks/), [fields,
  models, and model managers](/fr/3.1/topics/checks/#field-checking) all implement a `check()`
  method that is registered with the check framework. If you have an existing
  method called `check()` on one of these objects, you will need to rename it.
- As noted above in the « Cache » section of « Minor Features », defining the
  [`TIMEOUT`](/fr/3.1/ref/settings/#std-setting-CACHES-TIMEOUT) argument of the
  [`CACHES`](/fr/3.1/ref/settings/#std-setting-CACHES) setting as `None` will set the cache keys as
  « non-expiring ». Previously, with the memcache backend, a
  [`TIMEOUT`](/fr/3.1/ref/settings/#std-setting-CACHES-TIMEOUT) of `0` would set non-expiring keys,
  but this was inconsistent with the set-and-expire (i.e. no caching) behavior
  of `set("key", "value", timeout=0)`. If you want non-expiring keys,
  please update your settings to use `None` instead of `0` as the latter
  now designates set-and-expire in the settings as well.
- The `sql*` management commands now respect the `allow_migrate()` method
  of [`DATABASE_ROUTERS`](/fr/3.1/ref/settings/#std-setting-DATABASE_ROUTERS). If you have models synced to non-default
  databases, use the `--database` flag to get SQL for those models
  (previously they would always be included in the output).
- Decoding the query string from URLs now falls back to the ISO-8859-1 encoding
  when the input is not valid UTF-8.
- With the addition of the
  `django.contrib.auth.middleware.SessionAuthenticationMiddleware` to
  the default project template (pre-1.7.2 only), a database must be created
  before accessing a page using [`runserver`](/fr/3.1/ref/django-admin/#django-admin-runserver).
- The addition of the `schemes` argument to `URLValidator` will appear
  as a backwards-incompatible change if you were previously using a custom
  regular expression to validate schemes. Any scheme not listed in `schemes`
  will fail validation, even if the regular expression matches the given URL.

## Fonctionnalités déconseillées dans 1.7

### `django.core.cache.get_cache`

`django.core.cache.get_cache` has been supplanted by
[`django.core.cache.caches`](/fr/3.1/topics/cache/#django.core.cache.caches).

### `django.utils.dictconfig`/`django.utils.importlib`

`django.utils.dictconfig` and `django.utils.importlib` were copies of
respectively [`logging.config`](https://docs.python.org/3/library/logging.config.html#module-logging.config) and [`importlib`](https://docs.python.org/3/library/importlib.html#module-importlib) provided for Python
versions prior to 2.7. They have been deprecated.

### `django.utils.module_loading.import_by_path`

The current `django.utils.module_loading.import_by_path` function
catches `AttributeError`, `ImportError`, and `ValueError` exceptions,
and re-raises [`ImproperlyConfigured`](/fr/3.1/ref/exceptions/#django.core.exceptions.ImproperlyConfigured). Such
exception masking makes it needlessly hard to diagnose circular import
problems, because it makes it look like the problem comes from inside Django.
It has been deprecated in favor of
[`import_string()`](/fr/3.1/ref/utils/#django.utils.module_loading.import_string).

### `django.utils.tzinfo`

`django.utils.tzinfo` provided two [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) subclasses,
`LocalTimezone` and `FixedOffset`. They’ve been deprecated in favor of
more correct alternatives provided by [`django.utils.timezone`](/fr/3.1/ref/utils/#module-django.utils.timezone),
[`django.utils.timezone.get_default_timezone()`](/fr/3.1/ref/utils/#django.utils.timezone.get_default_timezone) and
[`django.utils.timezone.get_fixed_timezone()`](/fr/3.1/ref/utils/#django.utils.timezone.get_fixed_timezone).

### `django.utils.unittest`

`django.utils.unittest` provided uniform access to the `unittest2` library
on all Python versions. Since `unittest2` became the standard library’s
[`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest) module in Python 2.7, and Django 1.7 drops support for older
Python versions, this module isn’t useful anymore. It has been deprecated. Use
[`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest) instead.

### `django.utils.datastructures.SortedDict`

As [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) was added to the standard library in
Python 2.7, `SortedDict` is no longer needed and has been deprecated.

The two additional, deprecated methods provided by `SortedDict` (`insert()`
and `value_for_index()`) have been removed. If you relied on these methods to
alter structures like form fields, you should now treat these `OrderedDict`s
as immutable objects and override them to change their content.

For example, you might want to override `MyFormClass.base_fields` (although
this attribute isn’t considered a public API) to change the ordering of fields
for all `MyFormClass` instances; or similarly, you could override
`self.fields` from inside `MyFormClass.__init__()`, to change the fields
for a particular form instance. For example (from Django itself):

```
PasswordChangeForm.base_fields = OrderedDict(
    (k, PasswordChangeForm.base_fields[k])
    for k in ['old_password', 'new_password1', 'new_password2']
)
```

### Custom SQL location for models package

Previously, if models were organized in a package (`myapp/models/`) rather
than simply `myapp/models.py`, Django would look for initial SQL data in
`myapp/models/sql/`. This bug has been fixed so that Django
will search `myapp/sql/` as documented. After this issue was fixed, migrations
were added which deprecates initial SQL data. Thus, while this change still
exists, the deprecation is irrelevant as the entire feature will be removed in
Django 1.9.

### Réorganisation de `django.contrib.sites`

`django.contrib.sites` provides reduced functionality when it isn’t in
[`INSTALLED_APPS`](/fr/3.1/ref/settings/#std-setting-INSTALLED_APPS). The app-loading refactor adds some constraints in
that situation. As a consequence, two objects were moved, and the old
locations are deprecated:

- [`RequestSite`](/fr/3.1/ref/contrib/sites/#django.contrib.sites.requests.RequestSite) now lives in
  `django.contrib.sites.requests`.
- [`get_current_site()`](/fr/3.1/ref/contrib/sites/#django.contrib.sites.shortcuts.get_current_site) now lives in
  `django.contrib.sites.shortcuts`.

### l’attribut `declared_fieldsets` dans `ModelAdmin`

`ModelAdmin.declared_fieldsets` has been deprecated. Despite being a private
API, it will go through a regular deprecation path. This attribute was mostly
used by methods that bypassed `ModelAdmin.get_fieldsets()` but this was
considered a bug and has been addressed.

### Réorganisation de `django.contrib.contenttypes`

Since `django.contrib.contenttypes.generic` defined both admin and model
related objects, an import of this module could trigger unexpected side effects.
As a consequence, its contents were split into [`contenttypes`](/fr/3.1/ref/contrib/contenttypes/#module-django.contrib.contenttypes)
submodules and the `django.contrib.contenttypes.generic` module is deprecated:

- [`GenericForeignKey`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericForeignKey) and
  [`GenericRelation`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericRelation) now live in
  [`fields`](/fr/3.1/ref/contrib/contenttypes/#module-django.contrib.contenttypes.fields).
- [`BaseGenericInlineFormSet`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.forms.BaseGenericInlineFormSet) and
  [`generic_inlineformset_factory()`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.forms.generic_inlineformset_factory) now
  live in [`forms`](/fr/3.1/ref/contrib/contenttypes/#module-django.contrib.contenttypes.forms).
- [`GenericInlineModelAdmin`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.admin.GenericInlineModelAdmin),
  [`GenericStackedInline`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.admin.GenericStackedInline) and
  [`GenericTabularInline`](/fr/3.1/ref/contrib/contenttypes/#django.contrib.contenttypes.admin.GenericTabularInline) now live in
  [`admin`](/fr/3.1/ref/contrib/contenttypes/#module-django.contrib.contenttypes.admin).

### `syncdb`

The `syncdb` command has been deprecated in favor of the new [`migrate`](/fr/3.1/ref/django-admin/#django-admin-migrate)
command. `migrate` takes the same arguments as `syncdb` used to plus a few
more, so it’s safe to just change the name you’re calling and nothing else.

### les modules `util` renommés en `utils`

The following instances of `util.py` in the Django codebase have been renamed
to `utils.py` in an effort to unify all util and utils references:

- `django.contrib.admin.util`
- `django.contrib.gis.db.backends.util`
- `django.db.backends.util`
- `django.forms.util`

### la méthode `get_formsets` dans `ModelAdmin`

`ModelAdmin.get_formsets` has been deprecated in favor of the new
[`get_formsets_with_inlines()`](/fr/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_formsets_with_inlines), in order to
better handle the case of selectively showing inlines on a `ModelAdmin`.

### `IPAddressField`

The `django.db.models.IPAddressField` and `django.forms.IPAddressField`
fields have been deprecated in favor of
[`django.db.models.GenericIPAddressField`](/fr/3.1/ref/models/fields/#django.db.models.GenericIPAddressField) and
[`django.forms.GenericIPAddressField`](/fr/3.1/ref/forms/fields/#django.forms.GenericIPAddressField).

### `BaseMemcachedCache._get_memcache_timeout` method

The `BaseMemcachedCache._get_memcache_timeout()` method has been renamed to
`get_backend_timeout()`. Despite being a private API, it will go through the
normal deprecation.

### Natural key serialization options

The `--natural` and `-n` options for [`dumpdata`](/fr/3.1/ref/django-admin/#django-admin-dumpdata) have been
deprecated. Use [`dumpdata --natural-foreign`](/fr/3.1/ref/django-admin/#cmdoption-dumpdata-natural-foreign) instead.

Similarly, the `use_natural_keys` argument for `serializers.serialize()`
has been deprecated. Use `use_natural_foreign_keys` instead.

### Merging of `POST` and `GET` arguments into `WSGIRequest.REQUEST`

It was already strongly suggested that you use `GET` and `POST` instead of
`REQUEST`, because the former are more explicit. The property `REQUEST` is
deprecated and will be removed in Django 1.9.

### la classe `django.utils.datastructures.MergeDict`

`MergeDict` exists primarily to support merging `POST` and `GET`
arguments into a `REQUEST` property on `WSGIRequest`. To merge
dictionaries, use `dict.update()` instead. The class `MergeDict` is
deprecated and will be removed in Django 1.9.

### Codes de langue `zh-cn`, `zh-tw` et `fy-nl`

The currently used language codes for Simplified Chinese `zh-cn`,
Traditional Chinese `zh-tw` and (Western) Frysian `fy-nl` are deprecated
and should be replaced by the language codes `zh-hans`, `zh-hant` and
`fy` respectively. If you use these language codes, you should rename the
locale directories and update your settings to reflect these changes. The
deprecated language codes will be removed in Django 1.9.

### fonction `django.utils.functional.memoize`

The function `memoize` is deprecated and should be replaced by the
`functools.lru_cache` decorator (available from Python 3.2 onwards).

Django ships a backport of this decorator for older Python versions and it’s
available at `django.utils.lru_cache.lru_cache`. The deprecated function will
be removed in Django 1.9.

### Geo Sitemaps

Google has retired support for the Geo Sitemaps format. Hence Django support
for Geo Sitemaps is deprecated and will be removed in Django 1.8.

### Passing callable arguments to queryset methods

Callable arguments for querysets were an undocumented feature that was
unreliable. It’s been deprecated and will be removed in Django 1.9.

Callable arguments were evaluated when a queryset was constructed rather than
when it was evaluated, thus this feature didn’t offer any benefit compared to
evaluating arguments before passing them to queryset and created confusion that
the arguments may have been evaluated at query time.

### le réglage `ADMIN_FOR`

The `ADMIN_FOR` feature, part of the admindocs, has been removed. You can
remove the setting from your configuration at your convenience.

### `SplitDateTimeWidget` avec `DateTimeField`

`SplitDateTimeWidget` support in [`DateTimeField`](/fr/3.1/ref/forms/fields/#django.forms.DateTimeField) is
deprecated, use `SplitDateTimeWidget` with
[`SplitDateTimeField`](/fr/3.1/ref/forms/fields/#django.forms.SplitDateTimeField) instead.

### `validate`

The `validate` management command is deprecated in favor of the
[`check`](/fr/3.1/ref/django-admin/#django-admin-check) command.

### `django.core.management.BaseCommand`

`requires_model_validation` is deprecated in favor of a new
`requires_system_checks` flag. If the latter flag is missing, then the
value of the former flag is used. Defining both `requires_system_checks` and
`requires_model_validation` results in an error.

La méthode `check()` a remplacé l’ancienne méthode `validate()`.

### `ModelAdmin` validators

The `ModelAdmin.validator_class` and `default_validator_class` attributes
are deprecated in favor of the new `checks_class` attribute.

The `ModelAdmin.validate()` method is deprecated in favor of
`ModelAdmin.check()`.

The `django.contrib.admin.validation` module is deprecated.

### `django.db.backends.DatabaseValidation.validate_field`

This method is deprecated in favor of a new `check_field` method.
The functionality required by `check_field()` is the same as that provided
by `validate_field()`, but the output format is different. Third-party database
backends needing this functionality should provide an implementation of
`check_field()`.

### Loading `ssi` and `url` template tags from `future` library

Django 1.3 introduced `{% load ssi from future %}` and
`{% load url from future %}` syntax for forward compatibility of the
`ssi` and [`url`](/fr/3.1/ref/templates/builtins/#std-templatetag-url) template tags. This syntax is now deprecated and
will be removed in Django 1.9. You can simply remove the
`{% load ... from future %}` tags.

### `django.utils.text.javascript_quote`

`javascript_quote()` was an undocumented function present in `django.utils.text`.
It was used internally in the `javascript_catalog()` view
whose implementation was changed to make use of `json.dumps()` instead.
If you were relying on this function to provide safe output from untrusted
strings, you should use `django.utils.html.escapejs` or the
[`escapejs`](/fr/3.1/ref/templates/builtins/#std-templatefilter-escapejs) template filter.
If all you need is to generate valid JavaScript strings, you can simply use
`json.dumps()`.

### `fix_ampersands` utils method and template filter

The `django.utils.html.fix_ampersands` method and the `fix_ampersands`
template filter are deprecated, as the escaping of ampersands is already taken care
of by Django’s standard HTML escaping features. Combining this with `fix_ampersands`
would either result in double escaping, or, if the output is assumed to be safe,
a risk of introducing XSS vulnerabilities. Along with `fix_ampersands`,
`django.utils.html.clean_html` is deprecated, an undocumented function that calls
`fix_ampersands`.
As this is an accelerated deprecation, `fix_ampersands` and `clean_html`
will be removed in Django 1.8.

### Reorganization of database test settings

All database settings with a `TEST_` prefix have been deprecated in favor of
entries in a [`TEST`](/fr/3.1/ref/settings/#std-setting-DATABASE-TEST) dictionary in the database
settings. The old settings will be supported until Django 1.9. For backwards
compatibility with older versions of Django, you can define both versions of
the settings as long as they match.

### Support de FastCGI

FastCGI support via the `runfcgi` management command will be removed in
Django 1.9. Please deploy your project using WSGI.

### Moved objects in `contrib.sites`

Following the app-loading refactor, two objects in
`django.contrib.sites.models` needed to be moved because they must be
available without importing `django.contrib.sites.models` when
`django.contrib.sites` isn’t installed. Import `RequestSite` from
`django.contrib.sites.requests` and `get_current_site()` from
`django.contrib.sites.shortcuts`. The old import locations will work until
Django 1.9.

### `django.forms.forms.get_declared_fields()`

Django no longer uses this functional internally. Even though it’s a private
API, it’ll go through the normal deprecation cycle.

### Private Query Lookup APIs

Private APIs `django.db.models.sql.where.WhereNode.make_atom()` and
`django.db.models.sql.where.Constraint` are deprecated in favor of the new
[custom lookups API](/fr/3.1/ref/models/lookups/).

## Features removed in 1.7

These features have reached the end of their deprecation cycle and are removed
in Django 1.7. See [Features deprecated in 1.5](/fr/3.1/releases/1.5/#deprecated-features-1-5) for details, including how to
remove usage of these features.

- `django.utils.simplejson` est supprimé.
- `django.utils.itercompat.product` est supprimé.
- INSTALLED\_APPS and TEMPLATE\_DIRS are no longer corrected from a plain
  string into a tuple.
- [`HttpResponse`](/fr/3.1/ref/request-response/#django.http.HttpResponse),
  [`SimpleTemplateResponse`](/fr/3.1/ref/template-response/#django.template.response.SimpleTemplateResponse),
  [`TemplateResponse`](/fr/3.1/ref/template-response/#django.template.response.TemplateResponse),
  `render_to_response()`, [`index()`](/fr/3.1/ref/contrib/sitemaps/#django.contrib.sitemaps.views.index), and
  [`sitemap()`](/fr/3.1/ref/contrib/sitemaps/#django.contrib.sitemaps.views.sitemap) no longer take a `mimetype`
  argument
- [`HttpResponse`](/fr/3.1/ref/request-response/#django.http.HttpResponse) immediately consumes its content if it’s
  an iterator.
- The `AUTH_PROFILE_MODULE` setting, and the `get_profile()` method on
  the User model are removed.
- La commande de management `cleanup` est supprimée.
- Le script `daily_cleanup.py` est supprimé.
- [`select_related()`](/fr/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related) no longer has a
  `depth` keyword argument.
- The `get_warnings_state()`/`restore_warnings_state()`
  functions from [`django.test.utils`](/fr/3.1/topics/testing/advanced/#module-django.test.utils) and the `save_warnings_state()`/
  `restore_warnings_state()`
  [django.test.\*TestCase](/fr/3.1/topics/testing/tools/#django-testcase-subclasses) are removed.
- The `check_for_test_cookie` method in
  [`AuthenticationForm`](/fr/3.1/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm) is removed.
- The version of `django.contrib.auth.views.password_reset_confirm()` that
  supports base36 encoded user IDs
  (`django.contrib.auth.views.password_reset_confirm_uidb36`) is removed.
- The `django.utils.encoding.StrAndUnicode` mix-in is removed.
