On December 2, 2017, Django officially released version 2.0, which became the first major version upgrade in many years. So what changes and points should Django users pay attention to in 2.0?
1. Python compatibility
Django 2.0 supports Python 3.4, 3.5 and 3.6. Django officially strongly recommends the latest version of each series.
The bottom line is that Django 2.0 no longer supports Python2!
Django 1.11.x is the last version to support Python 2.7.
2. New features of 2.0
1. Simplified URL routing syntax
django.urls.path()
The syntax of methods is simpler.
For example the previous:
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
Can write:
path('articles/<int:year>/', views.year_archive),
The new syntax supports mandatory definition of parameter types. In the example, only the integer year parameter is accepted, and the string type is no longer accepted. At the same time, the "10000" year is also legal (although it is a 5-digit number), unlike the previous regex that can only accept 4-digit numbers.
The previous version's django.conf.urls.url()
approach has changed django.urls.re_path()
, but for backward compatibility, the old one remains, rather than being deprecated immediately. django.conf.urls.include()
Methods can now be django.urls
imported from , that is, you can use from django.urls import include, path, re_path
.
2. The admin background is more mobile friendly
Django's most popular admin background, with responsive features, supports mainstream mobile devices.
3. Window expressions
A new Window expression allows adding an OVER clause to a queryset.
4. Small features
django.contrib.admin background
New ModelAdmin.autocomplete_fields
properties and ModelAdmin.get_autocomplete_fields()
methods can now use the Select2 search box on foreign keys and many-to-many fields.
django.contrib.auth user authentication
The default number of iterations for PBKDF2 password hashes has been increased from 36000 to 100000.
django.contrib.gis geoframework
- Added MySQL support for AsGeoJSON, GeoHash and GeoHash methods, isvalid and distance queries;
- Add Azimuth and LineLocatePoint methods to support PostGIS and SpatiaLite;
- All GEOSGeometry imported from GeoJSON have SRID collection;
- Add
OSMWidget.default_zoom
properties for customizing the default zoom level of the map; - metadata is now readable and editable;
- Allows creation of GDALRaster objects in GDAL's internal virtual filesystem;
- The new
GDALBand.color_interp()
method returns the color description of the band.
django.contrib.postgres database
- ArrayAgg adds distinct parameter;
- new RandomUUID function;
django.contrib.postgres.indexes.GinIndex
Now supportsfastupdate
andgin_pending_list_limit
parameters;- The new GistIndex class allows to create GiST indexes in the database;
- inspectdb can now introspect JSONField and RangeFields.
django.contrib.sitemaps sitemaps
- Add the protocol parameter to the GenericSitemap constructor;
Cache
- cache.set_many() now returns a list of keys that failed to insert;
File Storage
File.open()
Can now be used for context managers such aswith file.open() as f:
;
FormsForms
SplitDateTimeWidget
andSplitHiddenDateTimeWidget
adddate_attrs
ANDtime_attrs
parameter for specifying HTML attributes forDateInput
AND ;TimeInput
- New
Form.errors.get_json_data()
method returns form errors of type dictionary to accommodate JSON type x responses;
Generic Views Generic Views
- New
ContextMixin.extra_context
properties allowView.as_view()
adding context in;
Management CommandsManagement Commands
- inspectdb now treats MySQL's unsigned integers as
PositiveIntegerField
eitherPositiveSmallIntegerField
; - Added
makemessages --add-location
options; - loaddata can now be read from standard input;
- Added
diffsettings --output
options;
MigrationsMigrations
- Added
squashmigrations --squashed-name
options;
Models
- Added StrIndex database function;
- For Oracle databases, AutoField and BigAutoField now generate an identity column;
QuerySet.iterator()
addchunk_size
parameters;QuerySet.earliest()
,QuerySet.latest()
andMeta.get_latest_by
can now be sorted by some fields;- Added ExtractQuarter method for DateField and DateTimeField;
- Added TruncQuarter method to intercept DateField and DateTimeField to the first day of the quarter;
db_tablespace
Add parameters for class-based indexing ;- To
QuerySet.select_for_update()
increase the of parameter, but only support PostgreSQL and Oracle databases; QuerySet.in_bulk()
addfield_name
parameters;CursorWrapper.callproc()
Now accepts an optional dictionary-type keyword argument;QuerySet.values_list()
Added named parameter to get the named tuple result;- The new FilteredRelation class allows adding an ON clause to the queryset;
Pagination Pagination
- Added
Paginator.get_page()
, can handle various illegal page parameters to prevent exceptions;
Requests and Responses
- Now, the runserver server supports HTTP 1.1;
Templates
- To improve
Engine.get_default()
usefulness in 3rd party modules, it will now return the first of multiple DjangoTemplates engines configured in TEMPLATES instead of popping up an ImproperlyConfigured error; - Custom template tags now receive mandatory keyword arguments;
Tests
- Add multithreading support for LiveServerTestCase;
Validators validator
- The new ProhibitNullCharactersValidator does not allow form inputs to be null for CharField and its subclasses;
3. Important backward incompatibility
1. Removed support for bytestrings in some places
For example, for reverse(), str() is now used instead of force_text().
2. The maximum length of AbstractUser.last_name is increased to 150
If you have a custom User model that extends AbstractUser, you need to generate and apply a database migration so that last_name
the maximum length becomes 150.
If you need to last_name
maintain the 30 character limit, you can use a custom form as follows:
from django.contrib.auth.forms import UserChangeForm
class MyUserChangeForm(UserChangeForm):
last_name = forms.CharField(max_length=30, required=False)
If you need to keep this constraint also in admin, you can use UserAdmin.form as follows:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
3. QuerySet.reverse() and last() cannot be used for sliced querysets
Using reverse and get-nearest on a sliced queryset will throw an exception like this:
>>> Model.objects.all()[:2].reverse()
Traceback (most recent call last):
...
TypeError: Cannot reverse a query once a slice has been taken.
4. Form fields no longer receive optional parameters as positional parameters
To prevent runtime errors and improve reliability. The previous method of passing parameters like the following is now wrong:
forms.IntegerField(25, 10)
To pass it like this:
forms.IntegerField(max_value=25, min_value=10)
5. Index no longer accepts positional parameters
For example the following usage will result in an exception:
models.Index(['headline', '-pub_date'], 'index_name')
To provide parameter keywords, rewrite as:
models.Index(fields=['headline', '-pub_date'], name='index_name')
6. call_command() will validate the options it receives
parser.add_argument
For admin commands that are customized with options instead of (), you need to add an stealth_options
attribute like this:
class MyCommand(BaseCommand):
stealth_options = ('option_name', ...)
7. SQLite now supports foreign key constraints
In addition, Django 2.0 also deprecated and removed some methods and attributes.
Summary: It doesn't seem to have changed much. I'm not a heavy user. I basically can't feel the change. How to use it or how to use it, ^-^!
Reprinted article: https://www.cnblogs.com/feixuelove1009/p/7989720.html