Automatically upgrade your Django projects.

Related tags

Djangodjango-upgrade
Overview

django-upgrade

https://img.shields.io/github/workflow/status/adamchainz/django-upgrade/CI/main?style=for-the-badge https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge https://img.shields.io/pypi/v/django-upgrade.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

Automatically upgrade your Django projects.

Installation

Use pip:

python -m pip install django-upgrade

Python 3.8 to 3.10 supported.

Or with pre-commit in the repos section of your .pre-commit-config.yaml file (docs):

-   repo: https://github.com/adamchainz/django-upgrade
    rev: ''  # replace with latest tag on GitHub
    hooks:
    -   id: django-upgrade
        args: [--target-version, "3.2"]   # Replace with Django version

Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.


Usage

django-upgrade is a commandline tool that rewrites files in place. Pass your Django version as <major>.<minor> to the --target-version flag. The built-in fixers will rewrite your code to avoid some DeprecationWarnings and use some new features on your Django version. For example:

django-upgrade --target-version 3.2 example/core/models.py example/settings.py

The --target-version flag defaults to 2.2, the oldest supported version when this project was created. For more on usage run django-upgrade --help.

django-upgrade focuses on upgrading your code for the “99% case” and not on making it look nice. Run django-upgrade before your reformatters, such as isort or Black.

The full list of fixers is documented below.

History

django-codemod is a pre-existing, more complete Django auto-upgrade tool, written by Bruno Alla. Unfortunately its underlying library LibCST is particularly slow, making it annoying to run django-codemod on every commit and in CI. Additionally LibCST only advertises support up to Python 3.8 (at time of writing).

django-upgrade is an experiment in reimplementing such a tool using the same techniques as the fantastic pyupgrade. The tool leans on the standard library’s ast and tokenize modules, the latter via the tokenize-rt wrapper. This means it will always be fast and support the latest versions of Python.

For a quick benchmark: running django-codemod against a medium Django repository with 153k lines of Python takes 133 seconds. pyupgrade and django-upgrade both take less than 0.5 seconds.

Fixers

Django 1.9

Release Notes

on_delete argument

Add on_delete=models.CASCADE to ForeignKey and OneToOneField:

-models.ForeignKey("auth.User")
+models.ForeignKey("auth.User", on_delete=models.CASCADE)

-models.OneToOneField("auth.User")
+models.OneToOneField("auth.User", on_delete=models.CASCADE)

Compatibility imports

Rewrites some compatibility imports:

  • django.forms.utils.pretty_name in django.forms.forms
  • django.forms.boundfield.BoundField in django.forms.forms

Whilst mentioned in the Django 3.1 release notes, these have been possible since Django 1.9.

-from django.forms.forms import pretty_name
+from django.forms.utils import pretty_name

Django 1.11

Release Notes

Compatibility imports

Rewrites some compatibility imports:

  • django.core.exceptions.EmptyResultSet in django.db.models.query, django.db.models.sql, and django.db.models.sql.datastructures
  • django.core.exceptions.FieldDoesNotExist in django.db.models.fields

Whilst mentioned in the Django 3.1 release notes, these have been possible since Django 1.11.

-from django.db.models.query import EmptyResultSet
+from django.core.exceptions import EmptyResultSet

-from django.db.models.fields import FieldDoesNotExist
+from django.core.exceptions import FieldDoesNotExist

Django 2.0

Release Notes

URL’s

Rewrites imports of include() and url() from django.conf.urls to django.urls. url() calls using compatible regexes are rewritten to the new path() syntax, otherwise they are converted to call re_path().

-from django.conf.urls import include, url
+from django.urls import include, path, re_path

 urlpatterns = [
-    url(r'^$', views.index, name='index'),
+    path('', views.index, name='index'),
-    url(r'^about/$', views.about, name='about'),
+    path('about/', views.about, name='about'),
-    url(r'^post/(?P<slug>[w-]+)/$', views.post, name='post'),
+    re_path(r'^post/(?P<slug>[w-]+)/$', views.post, name='post'),
-    url(r'^weblog/', include('blog.urls')),
+    path('weblog/', include('blog.urls')),
 ]

lru_cache

Rewrites imports of lru_cache from django.utils.functional to use functools.

-from django.utils.functional import lru_cache
+from functools import lru_cache

Django 2.2

Release Notes

HttpRequest.headers

Rewrites use of request.META to read HTTP headers to instead use request.headers.

-request.META['HTTP_ACCEPT_ENCODING']
+request.headers['Accept-Encoding']

-self.request.META.get('HTTP_SERVER', '')
+self.request.headers.get('Server', '')

QuerySetPaginator

Rewrites deprecated alias django.core.paginator.QuerySetPaginator to Paginator.

-from django.core.paginator import QuerySetPaginator
+from django.core.paginator import Paginator

-QuerySetPaginator(...)
+Paginator(...)

FixedOffset

Rewrites deprecated class FixedOffset(x, y)) to timezone(timedelta(minutes=x), y)

Known limitation: this fixer will leave code broken with an ImportError if FixedOffset is called with only *args or **kwargs.

-from django.utils.timezone import FixedOffset
-FixedOffset(120, "Super time")
+from datetime import timedelta, timezone
+timezone(timedelta(minutes=120), "Super time")

FloatRangeField

Rewrites model and form fields using FloatRangeField to DecimalRangeField, from the relevant django.contrib.postgres modules.

 from django.db.models import Model
-from django.contrib.postgres.fields import FloatRangeField
+from django.contrib.postgres.fields import DecimalRangeField

 class MyModel(Model):
-    my_field = FloatRangeField("My range of numbers")
+    my_field = DecimalRangeField("My range of numbers")

TestCase class database declarations

Rewrites the allow_database_queries and multi_db attributes of Django’s TestCase classes to the new databases attribute. This only applies in test files, which are heuristically detected as files with either “test” or “tests” somewhere in their path.

Note that this will only rewrite to databases = [] or databases = "__all__". With multiple databases you can save some test time by limiting test cases to the databases they require (which is why Django made the change).

 from django.test import SimpleTestCase

 class MyTests(SimpleTestCase):
-    allow_database_queries = True
+    databases = "__all__"

     def test_something(self):
         self.assertEqual(2 * 2, 4)

Django 3.0

Release Notes

django.utils.encoding aliases

Rewrites smart_text() to smart_str(), and force_text() to force_str().

-from django.utils.encoding import force_text, smart_text
+from django.utils.encoding import force_str, smart_str


-force_text("yada")
-smart_text("yada")
+force_str("yada")
+smart_str("yada")

django.utils.http deprecations

Rewrites the urlquote(), urlquote_plus(), urlunquote(), and urlunquote_plus() functions to the urllib.parse versions. Also rewrites the internal function is_safe_url() to url_has_allowed_host_and_scheme().

-from django.utils.http import urlquote
+from urllib.parse import quote

-escaped_query_string = urlquote(query_string)
+escaped_query_string = quote(query_string)

django.utils.text deprecation

Rewrites unescape_entities() with the standard library html.escape().

-from django.utils.text import unescape_entities
+import html

-unescape_entities("some input string")
+html.escape("some input string")

django.utils.translation deprecations

Rewrites the ugettext(), ugettext_lazy(), ugettext_noop(), ungettext(), and ungettext_lazy() functions to their non-u-prefixed versions.

-from django.utils.translation import ugettext as _, ungettext
+from django.utils.translation import gettext as _, ngettext

-ungettext("octopus", "octopodes", n)
+ngettext("octopus", "octopodes", n)

Django 3.1

Release Notes

JSONField

Rewrites imports of JSONField and related transform classes from those in django.contrib.postgres to the new all-database versions.

-from django.contrib.postgres.fields import JSONField
+from django.db.models import JSONField

PASSWORD_RESET_TIMEOUT_DAYS

Rewrites the setting PASSWORD_RESET_TIMEOUT_DAYS to PASSWORD_RESET_TIMEOUT, adding the multiplication by the number of seconds in a day.

Settings files are heuristically detected as modules with the whole word “settings” somewhere in their path. For example myproject/settings.py or myproject/settings/production.py.

-PASSWORD_RESET_TIMEOUT_DAYS = 4
+PASSWORD_RESET_TIMEOUT = 60 * 60 * 24 * 4

Signal

Removes the deprecated documentation-only providing_args argument.

 from django.dispatch import Signal
-my_cool_signal = Signal(providing_args=["documented", "arg"])
+my_cool_signal = Signal()

get_random_string

Injects the now-required length argument, with its previous default 12.

 from django.utils.crypto import get_random_string
-key = get_random_string(allowed_chars="01234567899abcdef")
+key = get_random_string(length=12, allowed_chars="01234567899abcdef")

NullBooleanField

Transforms the NullBooleanField() model field to BooleanField(null=True).

-from django.db.models import Model, NullBooleanField
+from django.db.models import Model, BooleanField

 class Book(Model):
-    valuable = NullBooleanField("Valuable")
+    valuable = BooleanField("Valuable", null=True)

Django 3.2

Release Notes

EmailValidator

Rewrites keyword arguments to their new names: whitelist to allowlist, and domain_whitelist to domain_allowlist.

 from django.core.validators import EmailValidator

-EmailValidator(whitelist=["example.com"])
+EmailValidator(allowlist=["example.com"])
-EmailValidator(domain_whitelist=["example.org"])
+EmailValidator(domain_allowlist=["example.org"])

Django 4.0

Release Notes

There are no fixers for Django 4.0 at current. Most of its deprecations don’t seem automatically fixable.

Owner
Adam Johnson
🦄 @django technical board member 🇬🇧 @djangolondon co-organizer ✍ AWS/Django/Python Author and Consultant
Adam Johnson
This is raw connection between redis server and django python app

Django_Redis This repository contains the code for this blogpost. Running the Application Clone the repository git clone https://github.com/xxl4tomxu9

Tom Xu 1 Sep 15, 2022
Sampling profiler for Python programs

py-spy: Sampling profiler for Python programs py-spy is a sampling profiler for Python programs. It lets you visualize what your Python program is spe

Ben Frederickson 9.5k Jan 01, 2023
Twitter Bootstrap for Django Form

Django bootstrap form Twitter Bootstrap for Django Form. A simple Django template tag to work with Bootstrap Installation Install django-bootstrap-for

tzangms 557 Oct 19, 2022
It's the assignment 1 from the Python 2 course, that requires a ToDoApp with authentication using Django

It's the assignment 1 from the Python 2 course, that requires a ToDoApp with authentication using Django

0 Jan 20, 2022
Django-static-site - A simple content site framework that harnesses the power of Django without the hassle

coltrane A simple content site framework that harnesses the power of Django with

Adam Hill 57 Dec 06, 2022
MAC address Model Field & Form Field for Django apps

django-macaddress MAC Address model and form fields for Django We use netaddr to parse and validate the MAC address. The tests aren't complete yet. Pa

49 Sep 04, 2022
Django/Jinja template indenter

DjHTML A pure-Python Django/Jinja template indenter without dependencies. DjHTML is a fully automatic template indenter that works with mixed HTML/CSS

Return to the Source 378 Jan 01, 2023
Resolve form field arguments dynamically when a form is instantiated

django-forms-dynamic Resolve form field arguments dynamically when a form is instantiated, not when it's declared. Tested against Django 2.2, 3.2 and

DabApps 108 Jan 03, 2023
Django API that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format).

"Casares News" API Api that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format). Usage Consume the articles

Andrés Milla 6 May 12, 2022
django-tables2 - An app for creating HTML tables

django-tables2 - An app for creating HTML tables django-tables2 simplifies the task of turning sets of data into HTML tables. It has native support fo

Jan Pieter Waagmeester 1.6k Jan 03, 2023
wagtail_tenants is a Django/Wagtail app to provide multitenancy to your wagtail project.

wagtail-tenants wagtail_tenants is a Django/Wagtail app to provide multitenancy to your wagtail project. You are able to run a main Wagtail Site and f

<bbr> 11 Nov 20, 2022
A Django backed for PostgreSQL using Psycopg 3

A Django backend for PostgreSQL using Psycopg 2 The backend passes the entire Django test suite, but it needs a few modifications to Django and to i

Daniele Varrazzo 42 Dec 16, 2022
Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.

django-mongonaut Info: An introspective interface for Django and MongoDB. Version: 0.2.21 Maintainer: Jazzband (jazzband.co) This Project is Being Mov

Jazzband 238 Dec 26, 2022
Basic Form Web Development using Python, Django and CSS

thebookrain Basic Form Web Development using Python, Django and CSS This is a basic project that contains two forms - borrow and donate. The form data

Ananya Dhulipala 1 Nov 27, 2021
Djang Referral System

Djang Referral System About | Features | Technologies | Requirements | Starting | License | Author 🎯 About I created django referral system and I wan

Alex Kotov 5 Oct 25, 2022
A app for managing lessons with Django

Course Notes A app for managing lessons with Django Some Ideas

Motahhar.Mokfi 6 Jan 28, 2022
CRUD with MySQL, Django and Sass.

CRUD with MySQL, Django and Sass. To have the same data in db: insert into crud_employee (first_name, last_name, email, phone, location, university) v

Luis Quiñones Requelme 1 Nov 19, 2021
Django + AWS Elastic Transcoder

Django Elastic Transcoder django-elastic-transcoder is an Django app, let you integrate AWS Elastic Transcoder in Django easily. What is provided in t

StreetVoice 66 Dec 14, 2022
Highlight the keywords of a page if a visitor is coming from a search engine.

Django-SEKH Django Search Engine Keywords Highlighter, is a middleware for Django providing the capacities to highlight the user's search keywords if

Julien Fache 24 Oct 08, 2021
Official clone of the Subversion repository.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. All documentation is in the "docs" directo

Raymond Penners 3 May 06, 2022