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.
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.
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 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
and
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
or 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.
It is not advised to have apps without migrations depend on (have a
ForeignKey
or
ManyToManyField
to) apps with migrations.
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 :
ready()
de leur configuration.models.py
. Vous n’avez plus besoin de régler explicitement app_label
.models.py
entièrement si une application ne possède pas de modèles.label
des configurations d’application, afin de contourner des conflits de nommage d’étiquettes.verbose_name
des configurations d’application.autodiscover()
au lancement de Django. Vous pouvez donc supprimer cette ligne de votre URLconf.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
: Le nom d’attribut du champ sur son modèle parent, ou None s’il ne fait pas partie d’un modèlepath
: 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 dictCes 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.
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 :
QuerySet
personnalisée et ses méthodes sur mesure étaient perdues après le premier appel à values()
ou values_list()
.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()
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()
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()
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 « 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.
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()
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.
Form
¶Form.add_error()
¶Auparavant, il y avait deux principaux modèles de gestion des erreurs dans les formulaires :
ValidationError
à partir de certaines fonctions (e.g. Field.clean()
, Form.clean_<fieldname>()
, ou Form.clean()
pour les erreurs n’ayant pas attrait aux champs)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()
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()
.
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.
Des changements profonds au niveau des différents conteneurs d’erreur furent nécessaires afin de supporter les caractéristiques ci-dessus, à savoir :attr Form.errors <django.forms.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.
django.contrib.admin
¶site_header
, site_title
et index_title
sur un 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 !django.contrib.admin
utilise maintenant la propriété CSS border-radius
pour les coins arrondis plutôt que des images de fond GIF.app-<app_name>
and model-<model_name>
dans leur balise <body>
pour permettre la personnalisation de la CSS par application ou par modèle.field-<field_name>
dans le code HTML pour permettre les personnalisations stylistiques.django.contrib.admin.ModelAdmin.get_search_fields()
.ModelAdmin.get_fields()
peut être étendue pour personnaliser la valeur de ModelAdmin.fields
.admin.site.register
existante, vous pouvez utiliser le nouveau décorateur register()
pour enregistrer un ModelAdmin
.ModelAdmin.list_display_links
= None
pour désactiver les liens sur la grille de la page de liste des objets pour modification.ModelAdmin.view_on_site
pour contrôler l’affichage ou non du lien « Voir sur le site ».ModelAdmin.list_display
en faisant précéder la valeur de admin_order_field
avec un tiret.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
¶**kwargs
passés à email_user()
sont transmis lors de l’appel sous-jacent à send_mail()
.permission_required()
peut tout aussi bien prendre une liste d’autorisations qu’une seule autorisation.AuthenticationForm.confirm_login_allowed()
afin de personnaliser plus facilement la politique d’ouverture de session.django.contrib.auth.views.password_reset()
prend un paramètre html_email_template_name
facultatif utilisé pour envoyer un e-mail HTML en plusieurs parties pour les réinitialisations du mot de passe.AbstractBaseUser.get_session_auth_hash()
method was added and if your AUTH_USER_MODEL
inherits from
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 for more details.django.contrib.formtools
¶WizardView.done()
now include a
form_dict
to allow easier access to forms by their step name.django.contrib.gis
¶crosses
, disjoint
, overlaps
, touches
et within
, si GEOS 3.3 ou ultérieur est installé.django.contrib.messages
¶django.contrib.messages
qui utilisent des cookies respectent maintenant les réglages SESSION_COOKIE_SECURE
et SESSION_COOKIE_HTTPONLY
.DEFAULT_MESSAGE_LEVELS
.Message
ont maintenant un attribut level_tag
qui contient la représentation textuelle du niveau de message.django.contrib.redirects
¶RedirectFallbackMiddleware
a deux nouveaux attributs (response_gone_class
et response_redirect_class
) qui spécifient les types d’instances HttpResponse
retournées par le middleware.django.contrib.sessions
¶"django.contrib.sessions.backends.cached_db"
respecte maintenant SESSION_CACHE_ALIAS
. Dans les versions précédentes, il utilisait toujours le cache default.django.contrib.sitemaps
¶lastmod
pour définir un en-tête Last-Modified
dans la réponse. Cela permet au ConditionalGetMiddleware
de gérer des requêtes GET
conditionnelles pour les plans de site qui définissent lastmod
.django.contrib.sites
¶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
et directory_permissions_mode
. Voir collectstatic
pour un exemple d’utilisation.
The CachedStaticFilesStorage
backend gets a sibling class called
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
management command and should
be a less expensive alternative for remote storages such as 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é. Voir findstatic
par un exemple de sortie.
django.contrib.syndication
¶updated
du flux de syndication Atom1Feed
utilise maintenant updateddate
au lieu de pubdate
, permettant à l’élément published
d’être inclut dans le flux (qui repose sur pubdate
).CACHES
is now available via
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.django.core.cache.caches
génère maintenant différentes instances par thread.TIMEOUT
du réglage 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.CSRF_COOKIE_AGE
facilite l’utilisation des cookies de session CSRF.send_mail()
accepte désormais un paramètre html_message
pour envoyer un courriel text/plain
et text/html
en plusieurs parties.EmailBackend
now accepts a
timeout
parameter.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.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
le fait pour les fichiers.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.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.<label>
et <input>
rendues par RadioSelect
et 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.<textarea>
rendues par Textarea
incluent maintenant un attribut maxlength
si le champ de modèle TextField
possède un max_length
.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
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.clean()
d’un formulaire n’a plus besoin de retourner self.cleaned_data
. Si elle retourne un dictionnaire modifié alors il sera utilisé.coerce
de TypedChoiceField
retourne une valeur arbitraire.SelectDateWidget.months
can be used to
customize the wording of the months displayed in the select widget.min_num
et validate_min
ont été ajoutées à formset_factory()
pour permettre la validation d’un nombre minimum de formulaires soumis.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.Form
lors d’un sous-classement en définissant son nom à None
.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 pour plus de détails.django.middleware.locale.LocaleMiddleware.response_redirect_class
vous permet de personnaliser les redirections émises par le middleware.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
. 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.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.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.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.LANGUAGE_COOKIE_AGE
, LANGUAGE_COOKIE_DOMAIN
et LANGUAGE_COOKIE_PATH
.The new --no-color
option for django-admin
disables the
colorization of management command output.
The new dumpdata --natural-foreign
and 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
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 :
compilemessages
.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é.
QuerySet.update_or_create()
a été ajoutée.Meta
de modèle default_permissions
vous permet de personnaliser (ou de désactiver) la création des autorisations d’ajout, modification et suppression, par défaut.OneToOneField
explicites pour l”Héritage multi-table sont maintenant découverts dans les classes abstraites.OneToOneField
by setting its
related_name
to
'+'
or ending it with '+'
.expressions F
supporte l’opérateur puissance (**
).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
.None
comme valeur de requête pour la recherche iexact
.limit_choices_to
lors de la définition d’un ForeignKey
ou d’un ManyToManyField
.only()
et defer()
sur le résultat de 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).index_together
(plutôt qu’une liste de listes) lors de la spécification d’un seul ensemble de champs.ManyToManyField.through_fields
.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é.order_by()
de façon explicite avec un champ de relation _id
en utilisant son nom d’attribut.enter
a été ajouté au signal setting_changed
.str
au format 'app_label.ModelName'
– tout comme les champs connexes – pour référencer de manière paresseuse leurs émetteurs.Context.push()
retourne maintenant un gestionnaire de contexte qui appelle automatiquement pop()
à la sortie de la déclaration with
. En outre, 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.Context.flatten()
retourne une pile de Context
sous la forme d’un dictionnaire unique à plat.Context
peuvent désormais être comparés pour l’égalité (en interne, cela utilise 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).widthratio
accepte maintenant un paramère "as"
pour capturer le résultat dans une variable.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()
.include
.TEMPLATE_DEBUG
is True
. This allows template origins to be
inspected and logged outside of the django.template
infrastructure.TypeError
ne sont plus réduites au silence lorsqu’elles sont levées au cours du rendu d’un gabarit.dirs
parameter which is a list or
tuple to override TEMPLATE_DIRS
:django.template.loader.get_template()
django.template.loader.select_template()
django.shortcuts.render()
django.shortcuts.render_to_response()
time
filter now accepts timezone-related format
specifiers 'e'
, 'O'
, 'T'
and 'Z'
and is able to digest time-zone-aware datetime
instances performing the expected
rendering.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.truncatechars_html
filter truncates a string to be no
longer than the specified number of characters, taking HTML into account.HttpRequest.scheme
attribute
specifies the scheme of the request (http
or https
normally).redirect()
now supports
relative URLs.JsonResponse
subclass of
HttpResponse
helps easily create JSON-encoded responses.DiscoverRunner
has two new attributes,
test_suite
and
test_runner
, which facilitate
overriding the way tests are collected and run.fetch_redirect_response
argument was added to
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.assertRedirects()
.secure
argument was added to all the request methods of
Client
. If True
, the request will be made
through HTTPS.assertNumQueries()
now prints
out the list of executed queries if the assertion fails.WSGIRequest
instance generated by the test handler is now attached to
the django.test.Response.wsgi_request
attribute.TEST
.strip_tags()
(mais elle ne peut toujours pas garantir un résultat HTML sécurisé, comme indiqué dans la documentation).RegexValidator
now accepts the optional
flags
and
Boolean inverse_match
arguments.
The inverse_match
attribute
determines if the ValidationError
should
be raised when the regular expression pattern matches (True
) or does not
match (False
, by default) the provided value
. The
flags
attribute sets the flags
used when compiling a regular expression string.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()
now accepts addresses with
IPv6 literals, like example@[2001:db8::1]
, as specified in RFC 5321.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
.
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.
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.
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.
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.
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.
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 :
INSTALLED_APPS
or have an explicit
app_label
.Django will enforce these requirements as of version 1.9, after a deprecation period.
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.
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
raises LookupError
instead of returning None
when no
model is found.only_installed
argument of get_model
and get_models
no
longer exists, nor does the seed_cache
argument of get_model
.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
):
ValidationError
before adding them to its internal storage.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)
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.
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.
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.
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
.
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
.
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.
The django.core.files.uploadhandler.FileUploadHandler.new_file()
method is now passed an additional content_type_extra
parameter. If you
have a custom FileUploadHandler
that implements new_file()
, be sure it accepts this new parameter.
ModelFormSet
s no longer
delete instances when save(commit=False)
is called. See
can_delete
for instructions on how
to manually delete objects from deleted forms.
Loading empty fixtures emits a RuntimeWarning
rather than raising
CommandError
.
django.contrib.staticfiles.views.serve()
will now raise an
Http404
exception instead of
ImproperlyConfigured
when 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__()
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
two Model
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 raise TypeError
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 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:
django.contrib.auth.models.AbstractUser
no longer defines a
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
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 in STATIC_ROOT
when
tests are run. The ability to transparently serve all the static assets
(similarly to what one gets with DEBUG = True
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
. 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
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
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()
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
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 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
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
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, fields,
models, and model managers 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
argument of the
CACHES
setting as None
will set the cache keys as
« non-expiring ». Previously, with the memcache backend, a
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
. 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
.
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.
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']
)
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.
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 in
django.contrib.sites.requests
.get_current_site()
now lives in
django.contrib.sites.shortcuts
.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.
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
and
GenericRelation
now live in
fields
.BaseGenericInlineFormSet
and
generic_inlineformset_factory()
now
live in forms
.GenericInlineModelAdmin
,
GenericStackedInline
and
GenericTabularInline
now live in
admin
.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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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()
.
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.
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.
FastCGI support via the runfcgi
management command will be removed in
Django 1.9. Please deploy your project using WSGI.
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 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.
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é.HttpResponse
,
SimpleTemplateResponse
,
TemplateResponse
,
render_to_response()
, index()
, and
sitemap()
no longer take a mimetype
argumentHttpResponse
immediately consumes its content if it’s
an iterator.AUTH_PROFILE_MODULE
setting, and the get_profile()
method on
the User model are removed.cleanup
est supprimée.daily_cleanup.py
est supprimé.select_related()
no longer has a
depth
keyword argument.get_warnings_state()
/restore_warnings_state()
functions from django.test.utils
and the save_warnings_state()
/
restore_warnings_state()
django.test.*TestCase are removed.check_for_test_cookie
method in
AuthenticationForm
is removed.django.contrib.auth.views.password_reset_confirm()
that
supports base36 encoded user IDs
(django.contrib.auth.views.password_reset_confirm_uidb36
) is removed.django.utils.encoding.StrAndUnicode
mix-in is removed.déc. 02, 2017