Notes de publication de Django 1.7¶
2 Septembre 2014
Bienvenue dans Django 1.7 !
These release notes cover the new features, as well as some backwards incompatible changes 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, and some features have reached the end of their deprecation process and have been removed.
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, 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, mais quelques-unes des fonctionalités clés sont :
syncdb
a été dépréciée et remplacée parmigrate
. 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
anddjango.db.models.signals.post_syncdb
have been deprecated, to be replaced bypre_migrate
andpost_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éthodesallow_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 aRunPython
orRunSQL
operation in theoperations
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.It is not advised to have apps without migrations depend on (have a
ForeignKey
orManyToManyField
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 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()
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 explicitementapp_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
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
des configurations d’application. - L’interface d’administration appelle automatiquement
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
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, orNone
if it is not part of a modelpath
: 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 listekwargs
: 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.
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()
ouvalues_list()
. - La rédaction d’un
Manager
sur mesure était encore nécessaire afin de retourner la classeQuerySet
personnalisée et toutes les méthodes souhaitées sur le `` Manager`` devaient être redirigées vers laQuerySet
. L’ensemble du processus était contraire au principe DRY.
La méthode de classe QuerySet.as_manager()
peut désormais directement créer un Manager avec des méthodes de QuerySet :
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é 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 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
management command.
This command replaces the older validate
management command.
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. 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
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
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.
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
à partir de certaines fonctions (e.g.Field.clean()
,Form.clean_<fieldname>()
, ouForm.clean()
pour les erreurs n’ayant pas attrait aux champs) - Manipuler
Form._errors
en ciblant un champ spécifique dansForm.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()
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 pour un exemple utilisant Form.add_error()
.
Métadonnées d’erreur¶
Le constructeur de 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 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
.
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
.
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()
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
, Django.forms.utils.ErrorList
, et les stockages interne de 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 pour plus de détails.
Fonctionnalités mineures¶
django.contrib.admin
¶
- Vous pouvez maintenant implémenter les attributs
site_header
,site_title
etindex_title
sur unAdminSite
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
utilise maintenant la propriété CSSborder-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>
andmodel-<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()
. - La méthode
ModelAdmin.get_fields()
peut être étendue pour personnaliser la valeur deModelAdmin.fields
. - En plus de la syntaxe
admin.site.register
existante, vous pouvez utiliser le nouveau décorateurregister()
pour enregistrer unModelAdmin
. - Vous pouvez spécifier
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
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
en faisant précéder la valeur deadmin_order_field
avec un tiret. - La méthode
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
¶
- Tous
**kwargs
passés àemail_user()
sont transmis lors de l’appel sous-jacent àsend_mail()
. - Le décorateur
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()
afin de personnaliser plus facilement la politique d’ouverture de session. django.contrib.auth.views.password_reset()
takes an optionalhtml_email_template_name
parameter used to send a multipart HTML email for password resets.- The
AbstractBaseUser.get_session_auth_hash()
method was added and if yourAUTH_USER_MODEL
inherits fromAbstractBaseUser
, changing a user’s password now invalidates old sessions if thedjango.contrib.auth.middleware.SessionAuthenticationMiddleware
is enabled. See Invalidation de session lors du changement de mot de passe for more details.
django.contrib.formtools
¶
- Calls to
WizardView.done()
now include aform_dict
to allow easier access to forms by their step name.
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
etwithin
, si GEOS 3.3 ou ultérieur est installé.
django.contrib.messages
¶
- Les moteurs de
django.contrib.messages
qui utilisent des cookies respectent maintenant les réglagesSESSION_COOKIE_SECURE
etSESSION_COOKIE_HTTPONLY
. - Le processeur de contexte des messages ajoute maintenant un dictionnaire des niveaux par défaut sous le nom de
DEFAULT_MESSAGE_LEVELS
. Message
objects now have alevel_tag
attribute that contains the string representation of the message level.
django.contrib.redirects
¶
RedirectFallbackMiddleware
a deux nouveaux attributs (response_gone_class
etresponse_redirect_class
) qui spécifient les types d’instancesHttpResponse
retournées par le middleware.
django.contrib.sessions
¶
- The
"django.contrib.sessions.backends.cached_db"
session backend now respectsSESSION_CACHE_ALIAS
. In previous versions, it always used thedefault
cache.
django.contrib.sitemaps
¶
- L”
infrastructure de plan du site
utilise maintenantlastmod
pour définir un en-têteLast-Modified
dans la réponse. Cela permet auConditionalGetMiddleware
de gérer des requêtesGET
conditionnelles pour les plans de site qui définissentlastmod
.
django.contrib.sites
¶
- Le nouveau
django.contrib.sites.middleware.CurrentSiteMiddleware
permet de définir le site courant pour chaque requête.
django.contrib.staticfiles
¶
Les classes de stockage de fichiers statiques 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
etdirectory_permissions_mode
. Voircollectstatic
pour un exemple d’utilisation.Le moteur
CachedStaticFilesStorage
obtient une classe apparentée et nomméeManifestStaticFilesStorage
qui n’utilise pas du tout le système de cache, mais plutôt un fichier JSON appeléstaticfiles.json
pour stocker la correspondance entre le nom du fichier d’origine (e.g.css/styles.css
) et le nom du fichier haché (e.g.css/styles.55e7cbb9ba48.css
). Le fichierstaticfiles.json
est créé lors de l’exécution de la commande de gestioncollectstatic
et devrait être une alternative moins coûteuse pour les stockages distants tels que Amazon S3.Voir la documentation de
ManifestStaticFilesStorage
pour plus d’informations.findstatic
accepte maintenant une verbosité de niveau 2, ce qui signifie qu’elle affichera les chemins relatifs des répertoires qu’elle a recherché. Voirfindstatic
par un exemple de sortie.
django.contrib.syndication
¶
- L’élément
updated
du flux de syndicationAtom1Feed
utilise maintenantupdateddate
au lieu depubdate
, permettant à l’élémentpublished
d’être inclut dans le flux (qui repose surpubdate
).
Cache¶
- Access to caches configured in
CACHES
is now available viadjango.core.cache.caches
. This dict-like object provides a different instance per thread. It supersedesdjango.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
génère maintenant différentes instances par thread. - Définir l’argument
TIMEOUT
du réglageCACHES
àNone
définiera les clés du cache comme « n’expirant pas » par défaut. Auparavant, il était seulement possible de passertimeout = None
à la méthodeset()
des moteurs de cache.
Cross Site Request Forgery¶
- Le réglage
CSRF_COOKIE_AGE
facilite l’utilisation des cookies de session CSRF.
Email¶
send_mail()
now accepts anhtml_message
parameter for sending a multipart text/plain and text/html email.- The SMTP
EmailBackend
now accepts atimeout
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
contient les paramètres supplémentaires passés à l’en-têtecontent-type
lors d’un téléversement de fichier. - Le nouveau réglage
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 commeFILE_UPLOAD_PERMISSIONS
le fait pour les fichiers. - L’attribut
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()
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 parRadioSelect
etCheckboxSelectMultiple
lors de l’itération sur les boutons radio ou les cases à cocher incluent maintenant les attributsfor
etid
, respectivement. Chaque bouton radio ou case à cocher inclut un attributid_for_label
produisant l’ID de l’élément. - Les balises
<textarea>
rendues parTextarea
incluent maintenant un attributmaxlength
si le champ de modèleTextField
possède unmax_length
. Field.choices
permet désormais de personnaliser l’étiquette « empty choice » en incluant un tuple avec une chaîne vide ouNone
pour la clé et l’étiquette personnalisée en tant que valeur. L’option vide par défaut"----------"
sera omise dans ce cas.MultiValueField
autorisent les sous-champs facultatifs en réglant l’argumentrequire_all_fields
àFalse
. L’attributrequired
pour chaque champ individuel sera respecté, et une nouvelle erreur de validationincomplete
sera déclenchée lorsqu’un champ requis est vide.- La méthode
clean()
d’un formulaire n’a plus besoin de retournerself.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
deTypedChoiceField
retourne une valeur arbitraire. SelectDateWidget.months
can be used to customize the wording of the months displayed in the select widget.- Les paramètres
min_num
etvalidate_min
ont été ajoutées àformset_factory()
pour permettre la validation d’un nombre minimum de formulaires soumis. - Les métaclasses utilisées par
Form
etModelForm
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 deuxForm
etModelForm
a été supprimée tant queModelForm
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
, etunique_together
deModelForm
. Afin de supporterunique_together
ou tout autreNON_FIELD_ERROR
,ModelForm
regarde maintenant la cléNON_FIELD_ERROR
dans le dictionnaireerror_messages
de la classeMeta
interne àModelForm
. Voir les considérations concernant le error_messages du modèle pour plus de détails.
Internationalisation¶
- L’attribut
django.middleware.locale.LocaleMiddleware.response_redirect_class
vous permet de personnaliser les redirections émises par le middleware. - The
LocaleMiddleware
now stores the user’s selected language with the session key_language
. This should only be accessed using theLANGUAGE_SESSION_KEY
constant. Previously it was stored with the keydjango_language
and theLANGUAGE_SESSION_KEY
constant did not exist, but keys reserved for Django should start with an underscore. For backwards compatibilitydjango_language
is still read from in 1.7. Sessions will be migrated to the new key as they are written. - The
blocktrans
tag now supports atrimmed
option. This option will remove newline characters from the beginning and the end of the content of the{% blocktrans %}
tag, replace any whitespace at the beginning and end of a line and merge all lines into one using a space character to separate them. This is quite useful for indenting the content of a{% blocktrans %}
tag without having the indentation characters end up in the corresponding entry in the.po
file, which makes the translation process easier. - Lorsque vous exécutez
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 pour plus de détails. - The
makemessages
command now always adds the--previous
command line flag to themsgmerge
command, keeping previously translated strings in.po
files for fuzzy strings. - Les paramètres suivants ont été introduits pour régler les options du cookie de langue :
LANGUAGE_COOKIE_AGE
,LANGUAGE_COOKIE_DOMAIN
etLANGUAGE_COOKIE_PATH
. - Added Régionalisation des formats for Esperanto.
Commandes d’administration¶
The new
--no-color
option fordjango-admin
disables the colorization of management command output.The new
dumpdata --natural-foreign
anddumpdata --natural-primary
options, and the newuse_natural_foreign_keys
anduse_natural_primary_keys
arguments forserializers.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 thecreatecachetable
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
a reçu plusieurs améliorations :- On Linux systems, if pyinotify is installed, the development server will reload immediately when a file is changed. Previously, it polled the filesystem for changes every second. That caused a small delay before reloads and reduced battery life on laptops.
- 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
. - 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
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 Python library is installed.
Notez que cette pratique est déconseillée en faveur de l’opération
RunSQL
des migrations, qui bénéficie du comportement amélioré.
Modèles¶
- La méthode
QuerySet.update_or_create()
a été ajoutée. - La nouvelle option
Meta
de modèledefault_permissions
vous permet de personnaliser (ou de désactiver) la création des autorisations d’ajout, modification et suppression, par défaut. - Les
OneToOneField
explicites pour l”Héritage multi-table sont maintenant découverts dans les classes abstraites. - It is now possible to avoid creating a backward relation for
OneToOneField
by setting itsrelated_name
to'+'
or ending it with'+'
. - Les
expressions F
supporte l’opérateur puissance (**
). - Les méthodes
remove()
etclean()
des gestionnaires connexes créés parForeignKey
etGenericForeignKey
acceptent maintenant l’argument mot-clefbulk
pour contrôler l’utilisation ou non des opérations en vrac (i.e. en utilisantQuerySet.update()
). Par défaut,True
. - Il est maintenant possible d’utiliser
None
comme valeur de requête pour la rechercheiexact
. - Il est maintenant possible de passer un appelable comme valeur de l’attribut
limit_choices_to
lors de la définition d’unForeignKey
ou d’unManyToManyField
. - L’appel à
only()
etdefer()
sur le résultat deQuerySet.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
(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
. - 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
. 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()
de façon explicite avec un champ de relation_id
en utilisant son nom d’attribut.
Signaux¶
- L’argument
enter
a été ajouté au signalsetting_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()
retourne maintenant un gestionnaire de contexte qui appelle automatiquementpop()
à la sortie de la déclarationwith
. En outre,push()
accepte désormais des paramètres qui sont passés audict
du constructeur qui est utilisé pour construire le nouveau niveau de contexte. - La nouvelle méthode
Context.flatten()
retourne une pile deContext
sous la forme d’un dictionnaire unique à plat. - Les objets
Context
peuvent désormais être comparés pour l’égalité (en interne, cela utiliseContext.flatten()
de sorte que la structure interne de chaque pile deContext
n’a pas d’importance tant que leur version aplatie est identique). - La balise de gabarit
widthratio
accepte maintenant un paramère"as"
pour capturer le résultat dans une variable. - La balise de gabarit
include
acceptera aussi désormais toute chose avec une méthoderender()
(comme unTemplate
) comme argument. Les arguments sous forme de chaînes seront, comme toujours, recherchés à l’aide deget_template()
. - Il est maintenant possible d’inclure les gabarits récursivement avec
include
. - Template objects now have an origin attribute set when
TEMPLATE_DEBUG
isTrue
. This allows template origins to be inspected and logged outside of thedjango.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 overrideTEMPLATE_DIRS
:django.template.loader.get_template()
django.template.loader.select_template()
django.shortcuts.render()
django.shortcuts.render_to_response()
- The
time
filter now accepts timezone-related format specifiers'e'
,'O'
,'T'
and'Z'
and is able to digest time-zone-awaredatetime
instances performing the expected rendering. - The
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 optionalusing
keyword argument to control which cache it uses. - The new
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
attribute specifies the scheme of the request (http
orhttps
normally). - The shortcut
redirect()
now supports relative URLs. - The new
JsonResponse
subclass ofHttpResponse
helps easily create JSON-encoded responses.
Tests¶
DiscoverRunner
has two new attributes,test_suite
andtest_runner
, which facilitate overriding the way tests are collected and run.- The
fetch_redirect_response
argument was added toassertRedirects()
. Since the test client can’t fetch externals URLs, this allows you to useassertRedirects
with redirects that aren’t part of your Django app. - Correct handling of scheme when making comparisons in
assertRedirects()
. - The
secure
argument was added to all the request methods ofClient
. IfTrue
, the request will be made through HTTPS. 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 thedjango.test.Response.wsgi_request
attribute. - The database settings for testing have been collected into a dictionary
named
TEST
.
Utilitaires¶
- Amélioration de l’exactitude de
strip_tags()
(mais elle ne peut toujours pas garantir un résultat HTML sécurisé, comme indiqué dans la documentation).
Validateurs¶
RegexValidator
now accepts the optionalflags
and Booleaninverse_match
arguments. Theinverse_match
attribute determines if theValidationError
should be raised when the regular expression pattern matches (True
) or does not match (False
, by default) the providedvalue
. Theflags
attribute sets the flags used when compiling a regular expression string.URLValidator
now accepts an optionalschemes
argument which allows customization of the accepted URI schemes (instead of the defaultshttp(s)
andftp(s)
).validate_email()
now accepts addresses with IPv6 literals, likeexample@[2001:db8::1]
, as specified in RFC 5321.
Backwards incompatible changes in 1.7¶
Avertissement
In addition to the changes outlined in this section, be sure to review the deprecation plan 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, 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.
The requirement for all field arguments to be serializable 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, 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 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
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
for one of them and override its
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
. Refer to the section on
the new project layout in the 1.4 release notes for
migration instructions.
Vous devez vous assurez de :
- All models are defined in applications that are listed in
INSTALLED_APPS
or have an explicitapp_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
must now implement a
handle_app_config()
method instead of
handle_app()
. This method receives an AppConfig
instance instead of a models module.
Introspecting applications¶
Since 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
) 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
raisesLookupError
instead of returningNone
when no model is found.- The
only_installed
argument ofget_model
andget_models
no longer exists, nor does theseed_cache
argument ofget_model
.
Management commands and order of 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
. 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
, 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()
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()
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 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 for more
details.
pytz
may be required¶
If your project handles datetimes before 1970 or after 2037 and Django raises
a ValueError
when encountering them, you will have to install
pytz. You may be affected by this problem if you use Django’s time
zone-related date formats or django.contrib.syndication
.
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()
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
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
au lieu de TestCase
.
Contrib middleware removed from default MIDDLEWARE_CLASSES
¶
The app-loading refactor
deprecated using models from apps which are not part of the
INSTALLED_APPS
setting. This exposed an incompatibility between
the default 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
,
AuthenticationMiddleware
, and
MessageMiddleware
were removed
from the defaults. These classes will still be included in the default settings
generated by 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()
method is now passed an additionalcontent_type_extra
parameter. If you have a customFileUploadHandler
that implementsnew_file()
, be sure it accepts this new parameter.ModelFormSet
s no longer delete instances whensave(commit=False)
is called. Seecan_delete
for instructions on how to manually delete objects from deleted forms.Loading empty fixtures emits a
RuntimeWarning
rather than raisingCommandError
.django.contrib.staticfiles.views.serve()
will now raise anHttp404
exception instead ofImproperlyConfigured
whenDEBUG
isFalse
. 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__()
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__()
method has changed such that twoModel
instances without primary key values won’t be considered equal (unless they are the same instance).The
django.db.models.Model.__hash__()
method will now raiseTypeError
when called on an instance without a primary key value. This is done to avoid mutable__hash__
values in containers.AutoField
columns in SQLite databases will now be created using theAUTOINCREMENT
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:django.contrib.auth.models.AbstractUser
no longer defines aget_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 inurlpatterns
. Define aget_absolute_url()
method on your own custom user object or useABSOLUTE_URL_OVERRIDES
if you want a URL for your user.The static asset-serving functionality of the
django.test.LiveServerTestCase
class has been simplified: Now it’s only able to serve content already present inSTATIC_ROOT
when tests are run. The ability to transparently serve all the static assets (similarly to what one gets withDEBUG = True
at development-time) has been moved to a new class that lives in thestaticfiles
application (the one actually in charge of such feature):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 currentCACHES
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 parentForm
.The
required
argument ofSelectDateWidget
has been removed. This widget now respects the form field’sis_required
attribute like other widgets.Widget.is_hidden
is now a read-only property, getting its value by introspecting the presence ofinput_type == 'hidden'
.select_related()
now chains in the same way as other similar calls likeprefetch_related
. That is,select_related('foo', 'bar')
is equivalent toselect_related('foo').select_related('bar')
. Previously the latter would have been equivalent toselect_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 setAUTOCOMMIT
toFalse
). 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 toallows_auto_pk_0
to better describe it. It’sTrue
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 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()
anddjango.utils.translation.trans_real.get_supported_language_variant()
now no longer have asupported
argument.The
shortcut
view indjango.contrib.contenttypes.views
now supports protocol-relative URLs (e.g.//example.com
).GenericRelation
now supports an optionalrelated_query_name
argument. Settingrelated_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
will need read access to the built-inpostgres
database. This is in lieu of the previous behavior of connecting to the actual non-test database.As part of the System check framework, fields, models, and model managers all implement a
check()
method that is registered with the check framework. If you have an existing method calledcheck()
on one of these objects, you will need to rename it.As noted above in the « Cache » section of « Minor Features », defining the
TIMEOUT
argument of theCACHES
setting asNone
will set the cache keys as « non-expiring ». Previously, with the memcache backend, aTIMEOUT
of0
would set non-expiring keys, but this was inconsistent with the set-and-expire (i.e. no caching) behavior ofset("key", "value", timeout=0)
. If you want non-expiring keys, please update your settings to useNone
instead of0
as the latter now designates set-and-expire in the settings as well.The
sql*
management commands now respect theallow_migrate()
method ofDATABASE_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 usingrunserver
.The addition of the
schemes
argument toURLValidator
will appear as a backwards-incompatible change if you were previously using a custom regular expression to validate schemes. Any scheme not listed inschemes
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
.
django.utils.dictconfig
/django.utils.importlib
¶
django.utils.dictconfig
and django.utils.importlib
were copies of
respectively logging.config
and 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
. 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()
.
django.utils.tzinfo
¶
django.utils.tzinfo
provided two tzinfo
subclasses,
LocalTimezone
and FixedOffset
. They’ve been deprecated in favor of
more correct alternatives provided by django.utils.timezone
,
django.utils.timezone.get_default_timezone()
and
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
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
instead.
django.utils.datastructures.SortedDict
¶
As 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
. The app-loading refactor adds some constraints in
that situation. As a consequence, two objects were moved, and the old
locations are deprecated:
RequestSite
now lives indjango.contrib.sites.requests
.get_current_site()
now lives indjango.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
submodules and the django.contrib.contenttypes.generic
module is deprecated:
GenericForeignKey
andGenericRelation
now live infields
.BaseGenericInlineFormSet
andgeneric_inlineformset_factory()
now live informs
.GenericInlineModelAdmin
,GenericStackedInline
andGenericTabularInline
now live inadmin
.
syncdb
¶
The syncdb
command has been deprecated in favor of the new 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()
, 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
and
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
have been
deprecated. Use 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 onward).
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
is
deprecated, use SplitDateTimeWidget
with
SplitDateTimeField
instead.
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
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
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
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.
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 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
,SimpleTemplateResponse
,TemplateResponse
,render_to_response()
,index()
, andsitemap()
no longer take amimetype
argumentHttpResponse
immediately consumes its content if it’s an iterator.- The
AUTH_PROFILE_MODULE
setting, and theget_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()
no longer has adepth
keyword argument.- The
get_warnings_state()
/restore_warnings_state()
functions fromdjango.test.utils
and thesave_warnings_state()
/restore_warnings_state()
django.test.*TestCase are removed. - The
check_for_test_cookie
method inAuthenticationForm
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.