• Django 1.7 release notes

  • Django 1.7 릴리즈 노트

  • September 2, 2014

  • 2014년 9월 2일

  • Welcome to Django 1.7!
  • 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 also dropped some features, which are detailed in our deprecation plan, we’vebegun the deprecation process for some features, and some features have reached the end of their deprecation process and have been removed.
  • 이 릴리즈 노트는 새로운 기능과 1.6 또는 그 이전 버전에서 업그레이드할 경우에 주의해야 할 하위 호환성 문제에 대한 것입니다. 기능 제거 계획(deprecation plan)에 따라 몇몇 기능은 탈락 되었으며, 일부는 제거 단계로 진입했으며, 또는 제거 완료 단계에 도달하여 제거되기도 했습니다.
  • Python compatibility

  • 파이썬 호환성

  • Django 1.7 requires Python 2.7 or above, though we highly recommend the latest minor release. Support for Python 2.6 has been dropped and support for Python 3.4 has been added.
  • Django 1.7은 Python 2.7 또는 그 이상을 요구하며, 가장 최신 마이너 릴리즈 버전을 사용하기를 강력 권장합니다. Python 2.6 지원은 종료되었으며, 대신 Python 3.4 지원이 추가되었습니다.
  • This change should affect only a small number of Django users, as most operating-system vendors today are shipping Python 2.7 or newer as their default version. If you’re still using Python 2.6, however, you’ll need to stick to Django 1.6 until you can upgrade your Python version. Per our support policy, Django 1.6 will continue to receive security support until the release of Django 1.8.
  • 요즘의 운영체제 벤더는 대부분 Python 2.7 또는 그 이상의 버전을 제공하므로, 변화는 몇몇 Django 사용자에게만 영향을 미칠 것입니다. 아직 Python 2.6을 사용하고 있다면 Python을 업그레이드하기 전까지는 Django 1.6에 머물러야 합니다. 우리의 지원 정책에 따라, Django 1.6은 Django 1.8을 릴리즈하기 전까지 보안 문제를 지원할 것입니다.
  • What’s new in Django 1.7

  • Django 1.7의 새로운 기능들

  • Schema migrations

  • 스키마 마이그레이션

  • Django now has built-in support for schema migrations. It allows models to be updated, changed, and deleted by creating migration files that represent the model changes and which can be run on any development, staging or production database.
  • 드디어 Django가 스키마 마이그레이션 기능을 내장하였습니다. 이는 모델 변경을 표현하는 스키마 마이그레이션 파일을 통해 모델의 갱신과 변경, 삭제 등이 가능해졌다는 의미입니다. 그리고 이 변경은 개발 환경이나 스테이징 또는 프로덕션 데이터베이스에 모두 적용 가능합니다.
  • Migrations are covered in their own documentation, but a few of the key features are:
  • 마이그레이션은 자체 도움말에서 다룰 테지만, 몇 가지 주요 기능을 꼽아본다면:
  • - syncdb has been deprecated and replaced by migrate. Don’t worry - calls to syncdb will still work as before.
  • - syncdb는 migrate로 대체되었습니다. 걱정하지 마세요. syncdb 명령어 자체는 예전처럼 그대로 사용할 수 있습니다.
  • - A new makemigrations command provides an easy way to autodetect changes to your models and make migrations for them.
  • - 새롭게 추가된 makemigrations 명령어는 모델의 변경점을 자동으로 찾아내 편리하게 마이그레이션할 수 있도록 해줍니다.
  • pre_syncdb and 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.
  • pre_syncdb와 post_syncdb는 pre_migrate와 post_migrate로 대체되었습니다. 이 새로운 신호(signal)는 전달인자가 조금 다릅니다. 문서를 통해 확인하세요.
  • - The allow_syncdb method on database routers is now called allow_migrate, but still performs the same function. Routers with allow_syncdb methods will still work, but that method name is deprecated and you should change it as soon as possible (nothing more than renaming is required).
  • - 데이터베이스 라우터에 있던 allow_syncdb는 allow_migrate로 불리게 되었지만, 여전히 같은 기능을 수행합니다. 라우터에 있는 allow_syncdb는 그대로 사용할 수 있지만 제거될 예정이므로 바꿔주는 것이 좋습니다(그냥 이름만 바꾸면 됩니다).
  • - initial_data fixtures are no longer loaded for apps with migrations; if you want to load initial data for an app, we suggest you do it in a migration.
  • - initial_data fixtures들은 마이그레이션에서 더 이상 사용되지 않습니다. 초기 데이터를 앱에서 불러오고 싶다면 마이그레이션을 사용하길 권합니다.
  • - Test rollback behavior is different for apps with migrations; in particular, Django will no longer emulate rollbacks on non-transactional databases or inside TransactionTestCase unless specifically requested.
  • - 롤백 테스트 과정이 앱의 마이그레이션에 따라 다르게 동작합니다. Django는 트랜잭션을 지원하지 않는 데이터베이스나 TransactionTestCase 안에서는 특별히 요청하지 않는 이상 롤백을 에뮬레이션하지 않습니다.
  • - It is not advised to have apps without migrations depend on (have a ForeignKey or ManyToManyField to) apps with migrations. Read the dependencies documentation for more.
  • - 마이그레이션이 없는 앱과 마이그레이션이 있는 앱 사이에 의존성을 추가하는 일(외래키나 ManyToManyField로 연결하는 등)은 권장되지 않습니다. 의존성 도움말을 참조하세요.
  • - If you are upgrading from South, see our Upgrading from South documentation, and third-party app authors should read theSouth 1.0 release notes for details on how to support South and Django migrations simultaneously.
  • - South를 사용하고 있었다면, Upgrading from South 문서를 참고하시길 바랍니다. 그리고 서드파티 앱 제작자들은 South 1.0 릴리즈 노트를 참고해서 South와 Django 마이그레이션을 어떻게 동시에 지원할 수 있는지 확인하십시오.
  • App-loading refactor

  • 앱 로딩 재설계

  • Historically, Django applications were tightly linked to models. A singleton known as the “app cache” dealt with both installed applications and models. The models module was used as an identifier for applications in many APIs.
  • 역사적으로, Django 애플리케이션은 모델과 강결합되어왔습니다. "App cache"라 불리우는 싱글톤이 설치된 애플리케이션과 모델을 다루고 있습니다. 모델 모듈은 여러 API에서 애플리케이션의 표식으로 많이 사용되었습니다.
  • As the concept of Django applications matured, this code showed some shortcomings. It has been refactored into an “app registry” where models modules no longer have a central role and where it’s possible to attach configuration data to applications.
  • Django application 컨셉이 성숙함에 따라 이런 코드에서 몇 가지 단점이 드러났습니다. 모델 모듈 중심의 설계를 "app registry"로 리팩터링하면서 설정 값들을 애플리케이션에 결합시킬 수 있게 되었습니다.
  • Improvements thus far include:
  • 개선된 점은 다음과 같습니다:
  • - Applications can run code at startup, before Django does anything else, with the ready() method of their configuration.
  • - 애플리케이션은 설정에 들어 있는 ready() 메소드를 통해 Django가 시작하는 시점에 코드를 실행할 수 있습니다.
  • - Application labels are assigned correctly to models even when they’re defined outside of models.py. You don’t have to setapp_label explicitly any more.
  • - 애플리케이션 레이블을 models.py 외부에서도 올바르게 지정할 수 있습니다. 더 이상 app_label을 사용할 필요가 없습니다.
  • - It is possible to omit models.py entirely if an application doesn’t have any models.
  • - 애플리케이션에 모델이 없는 경우에는 models.py를 생략해도 됩니다.
  • - Applications can be relabeled with the label attribute of application configurations, to work around label conflicts.
  • - 애플리케이션 설정에서 label을 변경할 수 있기 때문에 똑같은 레이블이 생성되는 문제를 피할 수 있습니다.
  • - The name of applications can be customized in the admin with the verbose_name of application configurations.
  • - Admin에 표시되는 애플리케이션 이름도 설정의 verbose_name을 통해 변경할 수 있습니다.
  • - The admin automatically calls autodiscover() when Django starts. You can consequently remove this line from your URLconf.
  • - Django가 시작될 때 admin에서 autodiscover()를 자동으로 호출하기 때문에 URLconf에서 해당 라인을 지워도 됩니다.
  • - Django imports all application configurations and models as soon as it starts, through a deterministic and straightforward process. This should make it easier to diagnose import issues such as import loops.
  • - 확정적이고 직관적인 프로세스 덕분에 Django는 애플리케이션 설정과 모델을 시작하자마자 읽어들일 수 있습니다. 이는 재귀 import와 같은 import 문제들을 쉽게 진단하는 데 도움이 됩니다.
  • New method on Field subclasses

  • Field 서브 클래스들의 새로운 기능들

  • To help power both schema migrations and to enable easier addition of composite keys in future releases of Django, the Field API now has a new required method: deconstruct().
  • 앞으로 릴리스될 Django에서 스키마 마이그레이션과 컴포짓 키 추가를 지원하기 위해 Field API에 deconstruct() 메서드가 추가되었습니다.
  • This method takes no arguments, and returns a tuple of four items:
  • 이 메서드는 인자를 취하지 않으며, 다음 네 가지 항목의 튜플을 리턴합니다.
  • - name: The field’s attribute name on its parent model, or None if it is not part of a model
  • - name: 부모 모델의 field attribute 이름. 모델에 없으면 None.
  • - path: A dotted, Python path to the class of this field, including the class name.
  • - path: 마침표(.)로 구분된 python path (클래스 이름을 포함)
  • note icon
    ex) "django.db.models.IntegerField"
  • - args: Positional arguments, as a list
  • - args: Positional arguments
  • - kwargs: Keyword arguments, as a dict
  • - kwargs: Keyword arguments
  • These four values allow any field to be serialized into a file, as well as allowing the field to be copied safely, both essential parts of these new features.
  • This change should not affect you unless you write custom Field subclasses; if you do, you may need to reimplement thedeconstruct() method if your subclass changes the method signature of __init__ in any way. If your field just inherits from a built-in Django field and doesn’t override __init__, no changes are necessary.
  • If you do need to override deconstruct(), a good place to start is the built-in Django fields (django/db/models/fields/__init__.py) as several fields, including DecimalField and DateField, override it and show how to call the method on the superclass and simply add or remove extra arguments.
  • This also means that all arguments to fields must themselves be serializable; to see what we consider serializable, and to find out how to make your own classes serializable, read the migration serialization documentation.
  • Calling custom QuerySet methods from the Manager

  • Historically, the recommended way to make reusable model queries was to create methods on a custom Manager class. The problem with this approach was that after the first method call, you’d get back a QuerySet instance and couldn’t call additional custom manager methods.
  • 지금까지, 재사용가능한 모델 쿼리를 만드는 데 추천되었던 방법은 커스텀 Manager 클래스에 메서드들을 만드는 것이었습니다. 하지만 이 방법으로는, 첫 번째 메서드를 호출하고 나면 QuerySet을 받기 때문에 커스텀 Manager의 메서드들을 더 이상 호출하지 못한다는 점이 문제가 되었습니다.
  • Though not documented, it was common to work around this issue by creating a custom QuerySet so that custom methods could be chained; but the solution had a number of drawbacks:
  • 그렇기 때문에 문서화되진 않았지만 이 문제를 해결하기 위해 쓰이던 흔한 방법은 커스텀 QuerySet을 만들어서 커스텀 메서드들을 체인으로 엮을 수 있게 하는 것입니다. 하지만 이 방법에도 문제가 많습니다.
  • - The custom QuerySet and its custom methods were lost after the first call to values() or values_list().
  • - 커스텀 QuerySet과 커스텀 메서드들은 values나 values_list를 호출하고 나면 사용할 수 없습니다.
  • - Writing a custom Manager was still necessary to return the custom QuerySet class and all methods that were desired on theManager had to be proxied to the QuerySet. The whole process went against the DRY principle.
  • - 커스텀 QuerySet 클래스를 반환하려고 할 때도 여전히 커스텀 Manager를 작성해야 하는데, 이 커스텀 Manager에 구현해야 하는 메서드들은 QuerySet을 반환하게 됩니다. 이런 과정은 DRY 원칙에 어긋납니다.
  • 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()
  • looah에서는 코드 들여쓰기가 제대로 나오지 않으므로...

    http://pastebin.com/e0gX6xAU 를 참고하세요
  • Using a custom manager when traversing reverse relations

  • 역참조를 할 때 커스텀 Manager 사용하기

  • It is now possible to specify a custom manager when traversing a reverse relationship:
  • 이제 커스텀 Manager를 명시하여 역참조(reverse relationship)를 할 수 있습니다.
  • New system check framework

  • 새로운 시스템 검사 프레임워크

  • We’ve added a new System check framework for detecting common problems (like invalid models) and providing hints for resolving those problems. The framework is extensible so you can add your own checks for your own apps and libraries.
  • 잘못된 모델 설계와 같은 일반적인 문제점을 찾아내고 이를 고칠 수 있게 해 주는 '시스템 검사 프레임워크'를 추가했습니다. 이 프레임워크에 사용자 고유의 검사 로직을 추가할 수도 있습니다.
  • To perform system checks, you use the check management command. This command replaces the older validate management command.
  • 시스템 검사를 실행하려면 'check'라는 명령어를 사용하면 됩니다. 이 명령은 과거의 'validate' 명령을 대체합니다.
  • New Prefetch object for advanced prefetch_related operations.

  • 고급 prefetch_related 작업 수행을 위한 새로운 Prefetch 객체

  • The new Prefetch object allows customizing prefetch operations.
  • 새로운 Prefetch 객체를 사용하면 prefetch 작업을 커스터마이징할 수 있습니다.
  • You can specify the QuerySet used to traverse a given relation or customize the storage location of prefetch results.
  • QuerySet에 어떤 연관 모델을 포함할지를 정할 수 있고, prefetch 결과물을 어디에 저장할지도 정할 수 있습니다.
  • This enables things like filtering prefetched relations, calling select_related() from a prefetched relation, or prefetching the same relation multiple times with different querysets. See prefetch_related() for more details.
  • Admin shortcuts support time zones

  • 어드민 바로가기가 시간대를 지원합니다.

  • The “today” and “now” shortcuts next to date and time input widgets in the admin are now operating in the current time zone. Previously, they used the browser time zone, which could result in saving the wrong value when it didn’t match the current time zone on the server.
  • 관리자 앱의 date와 time 위젯 옆에 있는 "today" 버튼과 "now" 버튼이 이제는 서버 설정 시간대를 기준으로 동작합니다. 이전에는 이 버튼들이 웹 브라우저의 시간대를 사용했기 때문에 서버의 시간대와 동일하지 않은 값이 저장되곤 했습니다.
  • In addition, the widgets now display a help message when the browser and server time zone are different, to clarify how the value inserted in the field will be interpreted.
  • 추가로, 브라우저와 서버의 시간대가 다를 경우 date 위젯과 time 위젯은 정확히 어떤 값이 사용되는지 도움말을 보여줍니다.
  • Using database cursors as context managers

  • 컨텍스트 매니저처럼 데이터베이스 커서 이용하기

  • Prior to Python 2.7, database cursors could be used as a context manager. The specific backend’s cursor defined the behavior of the context manager. The behavior of magic method lookups was changed with Python 2.7 and cursors were no longer usable as context managers.
  • Django 1.7 allows a cursor to be used as a context manager. That is, the following can be used:
  • 장고 1.7은 커서를 컨텍스트 매니저처럼 사용하는 것을 하용합니다. 다시 말해, 아래와 같은 사용이 가능합니다.
  • with connection.cursor() as c: c.execute(...)
  • with connection.cursor() as c: c.execute(...)
  • instead of:
  • 아래와 같은 방법 대신에
  • c = connection.cursor() try: c.execute(...) finally: c.close()
  • c = connection.cursor() try: c.execute(...) finally: c.close()
  • Custom lookups

  • 커스텀 lookups

  • It is now possible to write custom lookups and transforms for the ORM. Custom lookups work just like Django’s inbuilt lookups (e.g. lte, icontains) while transforms are a new concept.
  • The django.db.models.Lookup class provides a way to add lookup operators for model fields. As an example it is possible to addday_lte operator for DateFields.
  • The django.db.models.Transform class allows transformations of database values prior to the final lookup. For example it is possible to write a year transform that extracts year from the field’s value. Transforms allow for chaining. After the yeartransform has been added to DateField it is possible to filter on the transformed value, for exampleqs.filter(author__birthdate__year__lte=1981).
  • For more information about both custom lookups and transforms refer to the custom lookups documentation.
  • Improvements to Form error handling

  • 폼 오류 처리 개선사항

  • Form.add_error()

  • Form.add_error()

  • Previously there were two main patterns for handling errors in forms:
  • 이전까지 폼에서 오류를 조작하는 두 가지 주요 패턴은 다음과 같았습니다.
  • - Raising a ValidationError from within certain functions (e.g. Field.clean(), Form.clean_(), or Form.clean()for non-field errors.)
  • - 특정 함수 내에서 ValidationError 예외를 던지는 방법입니다. (예를 들어 Field.clean()과 Form.clean_필드이름()을 사용하거나 필드 에러가 아닌 경우에는 Form.clean()만 사용합니다.)
  • - Fiddling with Form._errors when targeting a specific field in Form.clean() or adding errors from outside of a “clean” method (e.g. directly from a view).
  • - Form.Clean()에서 특정한 필드를 대상으로 Form._errors를 수정한다거나, "clean" 메서드의 바깥에서 오류를 추가하는 방법입니다. (예를 들어 뷰에서)
  • Using the former pattern was straightforward since the form can guess from the context (i.e. which method raised the exception) where the errors belong and automatically process them. This remains the canonical way of adding errors when possible. However the latter was fiddly and error-prone, since the burden of handling edge cases fell on the user.
  • 이러한 패턴들은 오류가 어디에서 발생해서 어떻게 처리되는지를 폼에서 추측할 수 있는 경우(어떤 메서드가 예외를 던졌는가)에는 간단히 사용할 수 있는 방법이었습니다. 물론 이런 방식은 여전히 오류를 추가하는 정석이기도 합니다. 하지만 결국에는 예외 사항들을 다뤄야 하는 부담 때문에 성가시고 오류도 많이 발생합니다.
  • The new add_error() method allows adding errors to specific form fields from anywhere without having to worry about the details such as creating instances of django.forms.utils.ErrorList or dealing with Form.cleaned_data. This new API replaces manipulating Form._errors which now becomes a private API.
  • 새로운 add_error() 메서드를 이용하면django.forms.utils.ErrorList 인스턴스를 새로 생성한다거나 Form.cleaned_data를 다뤄야 하는 등의 걱정에서 벗어나 폼의 아무 필드에나 원하는 오류를 추가할 수 있습니다.
  • Error metadata

  • 오류 메타데이터

  • The ValidationError constructor accepts metadata such as error code or params which are then available for interpolating into the error message (see Raising ValidationError for more details); however, before Django 1.7 those metadata were discarded as soon as the errors were added to Form.errors.
  • ValidationError 생성자는 오류 코드나 오류 문구(더 자세한 정보는 ValidationError 예외 일으키기를 참고)에 삽입 가능한 매개변수 등의 metadata를 받습니다. 장고 1.7 이전에는 이러한 metadata는 오류가 Form.errors에 추가되자마자 무시되었습니다.
  • note icon
  • Form.errors and django.forms.utils.ErrorList now store the ValidationError instances so these metadata can be retrieved at any time through the new Form.errors.as_data method.
  • Form.errors와 django.forms.utils.ErrorList는 ValidationError 인스턴스에 저장되며, 이러한 metadata는 Form.errors.as_data 메서드를 통해 언제든 사용할 수 있습니다.
  • The retrieved ValidationError instances can then be identified thanks to their error code which enables things like rewriting the error’s message or writing custom logic in a view when a given error is present. It can also be used to serialize the errors in a custom format such as XML.
  • 이렇게 생성된 ValidationError 인스턴스는 오류 code를 통해 식별할 수 있이며, 덕분에 에러 메시지를 직접 쓸 수도 있고 특정 에러 발생시 뷰에서 처리할 수도 있습니다. 또한 이 기능을 이용해 오류들을 XML 같은 형식으로 저장할 수도 있습니다.
  • The new Form.errors.as_json() method is a convenience method which returns error messages along with error codes serialized as JSON. as_json() uses as_data() and gives an idea of how the new system could be extended.
  • 새로운 Form.errors.as_json() 메서드는 에러 메시지와 코드를 JSON 형태로 돌려주는 편의 메서드입니다. as_json() 메서드는 as_data() 메서드를 이용하며, 이는 시스템을 확장하는 방법의 단초를 제공합니다.
  • note icon
    여기서 new system이 뭘 가리키는 걸까요? 장고의 이후 버전들?
  • Error containers and backward compatibility

  • 에러 컨테이너와 하위 호환성

  • Heavy changes to the various error containers were necessary in order to support the features above, specifically Form.errors,django.forms.utils.ErrorList, and the internal storages of ValidationError. These containers which used to store error strings now store ValidationError instances and public APIs have been adapted to make this as transparent as possible, but if you’ve been using private APIs, some of the changes are backwards incompatible; see ValidationError constructor and internal storage for more details.
  • 위에 언급한 많은 기능들을 구현하기 위해 Form.errors와 django.forms.utils.ErrorList 그리고 ValidationError의 내부 저장소와 같은 에러 컨테이너들을 개선해야 했습니다. 이 컨테이너들은 이전까지는 에러 스트링을 저장했지만 이제는 ValidationError 인스턴스를 저장합니다. 공개용 API들은 이런 내용을 최대한 보이지 않게 구현했지만, 여러분이 비공개 API를 사용하고 싶다면 하위 호환성에 문제가 생길 수도 있습니다. 자세한 사항은 ValidationError constructor and internal storage를 참고하세요.
  • note icon
  • Minor features

  • 소소한 기능들

  • - You can now implement site_headersite_title, and index_title attributes on a custom AdminSite in order to easily change the admin site’s page title and header text. No more needing to override templates!
  • - 커스텀 AdminSite에서 site_header, site_title, index_title 속성을 사용할 수 있습니다. 이 속성들을 이용해서 커스텀 어드민 사이트 페이지에서 제목과 헤더 문구를 쉽게 바꿀 수 있습니다. 이제 템플릿 오버라이드를 하지 않아도 됩니다.
  • - Buttons in django.contrib.admin now use the border-radius CSS property for rounded corners rather than GIF background images.
  • - admin 페이지에서 둥근 사각형을 표현하기 위해 gif background를 쓰지 않고 border-radius CSS 속성을 사용합니다.
  • - Some admin templates now have app- and model- classes in their  tag to allow customizing the CSS per app or per model.
  • - 일부 admin 템플릿의 엘리먼트들은 body 태그에 app-<app_name>과 model-<model_name> CSS 클래스가 삽입되어, 앱이나 모델별로 CSS를 커스터마이징할 수 있습니다.
  • - The admin changelist cells now have a field- class in the HTML to enable style customizations.
  • - Admin의 changelist cell들의 스타일 커스터마이징을 위해 field-<field_name> CSS 클래스가 추가되었습니다.
  • - In addition to the existing admin.site.register syntax, you can use the new register() decorator to register aModelAdmin.
  • - You may now specify ModelAdmin.view_on_site to control whether or not to display the “View on site” link.
  • - You can specify a descending ordering for a ModelAdmin.list_display value by prefixing the admin_order_field value with a hyphen.
  • - Calls to WizardView.done() now include a form_dict to allow easier access to forms by their step name.
  • - The default OpenLayers library version included in widgets has been updated from 2.11 to 2.13.
  • - Prepared geometries now also support the crosses, disjoint, overlaps, touches and within predicates, if GEOS 3.3 or later is installed.
  • - Message objects now have a level_tag attribute that contains the string representation of the message level.
  • - The "django.contrib.sessions.backends.cached_db" session backend now respects SESSION_CACHE_ALIAS. In previous versions, it always used the default cache.
  • - 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.
  • - findstatic now accepts verbosity flag level 2, meaning it will show the relative paths of the directories it searched. Seefindstatic for example output.
  • - The Atom1Feed syndication feed’s updated element now utilizes updateddate instead of pubdate, allowing the publishedelement to be included in the feed (which relies on pubdate).
  • Cache

  • - If you instantiate cache backends directly, be aware that they aren’t thread-safe any more, as django.core.cache.cachesnow yields different instances per thread.
  • - Defining the TIMEOUT argument of the CACHES setting as None will set the cache keys as “non-expiring” by default. Previously, it was only possible to pass timeout=None to the cache backend’s set() method.
  • Cross Site Request Forgery

  • - The CSRF_COOKIE_AGE setting facilitates the use of session-based CSRF cookies.
  • Email

  • 이메일

  • - send_mail() now accepts an html_message parameter for sending a multipart text/plain and text/html email.
  • send_mail() 함수의 html_message 매개변수를 통해 text/plain 형태나 text/html 형태의 메일을 보낼 수 있습니다.
  • - The SMTP EmailBackend now accepts a timeout parameter.
  • SMTP EmailBackend에서도 timeout 매개변수를 지원합니다.
  • File Storage

  • - File locking on Windows previously depended on the PyWin32 package; if it wasn’t installed, file locking failed silently. That dependency has been removed, and file locking is now implemented natively on both Windows and Unix.
  • File Uploads

  • - The FileField.upload_to attribute is now optional. If it is omitted or given None or an empty string, a subdirectory won’t be used for storing the uploaded files.
  • - Uploaded files are now explicitly closed before the response is delivered to the client. Partially uploaded files are also closed as long as they are named file in the upload handler.
  • - Storage.get_available_name() now appends an underscore plus a random 7 character alphanumeric string (e.g."_x3a1gho"), rather than iterating through an underscore followed by a number (e.g. "_1", "_2", etc.) to prevent a denial-of-service attack. This change was also made in the 1.6.6, 1.5.9, and 1.4.14 security releases.
  • Forms

  • - The  and  tags rendered by RadioSelect and CheckboxSelectMultiple when looping over the radio buttons or checkboxes now include for and id attributes, respectively. Each radio button or checkbox includes an id_for_labelattribute to output the element’s ID.
  • - The  tags rendered by Textarea now include a maxlength attribute if the TextField model field has amax_length.
  • - Field.choices now allows you to customize the “empty choice” label by including a tuple with an empty string or None for the key and the custom label as the value. The default blank option "----------" will be omitted in this case.
  • - MultiValueField allows optional subfields by setting the require_all_fields argument to False. The required attribute for each individual field will be respected, and a new incomplete validation error will be raised when any required fields are empty.
  • - The clean() method on a form no longer needs to return self.cleaned_data. If it does return a changed dictionary then that will still be used.
  • - After a temporary regression in Django 1.6, it’s now possible again to make TypedChoiceField coerce method return an arbitrary value.
  • - The min_num and validate_min parameters were added to formset_factory() to allow validating a minimum number of submitted forms.
  • - The metaclasses used by Form and ModelForm have been reworked to support more inheritance scenarios. The previous limitation that prevented inheriting from both Form and ModelForm simultaneously have been removed as long as ModelFormappears first in the MRO.
  • - It’s now possible to remove a field from a Form when subclassing by setting the name to None.
  • - It’s now possible to customize the error messages for ModelForm’s unique, unique_for_date, and unique_togetherconstraints. In order to support unique_together or any other NON_FIELD_ERROR, ModelForm now looks for theNON_FIELD_ERROR key in the error_messages dictionary of the ModelForm’s inner Meta class. See considerations regarding model’s error_messages for more details.
  • Internationalization

  • - The LocaleMiddleware now stores the user’s selected language with the session key _language. This should only be accessed using the LANGUAGE_SESSION_KEY constant. Previously it was stored with the key django_language and theLANGUAGE_SESSION_KEY constant did not exist, but keys reserved for Django should start with an underscore. For backwards compatibility django_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 a trimmed 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.
  • - The makemessages command now always adds the --previous command line flag to the msgmerge command, keeping previously translated strings in po files for fuzzy strings.
  • Management Commands

  • - The --no-color option for django-admin.py allows you to disable the colorization of management command output.
  • - The new --natural-foreign and --natural-primary options for dumpdata, and the new use_natural_foreign_keys anduse_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.
  • - The runserver command received several improvements:
  • - 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.
  • - In addition, the development server automatically reloads when a translation file is updated, i.e. after runningcompilemessages.
  • - All HTTP requests are logged to the console, including requests for static files or favicon.ico that used to be filtered out.
  • - Management commands can now produce syntax colored output under Windows if the ANSICON third-party tool is installed and active.
  • - collectstatic command with symlink option is now supported on Windows NT 6 (Windows Vista and newer).
  • Note that it’s deprecated in favor of the RunSQL operation of migrations, which benefits from the improved behavior.
  • Models

  • - The new default_permissions model Meta option allows you to customize (or disable) creation of the default add, change, and delete permissions.
  • - Is it now possible to avoid creating a backward relation for OneToOneField by setting its related_name to '+' or ending it with '+'.
  • - The remove() and clear() methods of the related managers created by ForeignKey and GenericForeignKey now accept thebulk keyword argument to control whether or not to perform operations in bulk (i.e. using QuerySet.update()). Defaults toTrue.
  • - It is now possible to use None as a query value for the iexact lookup.
  • - It is now possible to pass a callable as value for the attribute limit_choices_to when defining a ForeignKey orManyToManyField.
  • - Calling only() and defer() on the result of QuerySet.values() now raises an error (before that, it would either result in a database error or incorrect data).
  • - You can use a single list for index_together (rather than a list of lists) when specifying a single set of fields.
  • - Custom intermediate models having more than one foreign key to any of the models participating in a many-to-many relationship are now permitted, provided you explicitly specify which foreign keys should be used by setting the newManyToManyField.through_fields argument.
  • - Assigning a model instance to a non-relation field will now throw an error. Previously this used to work if the field accepted integers as input as it took the primary key.
  • - Integer fields are now validated against database backend specific min and max values based on their internal_type. Previously model field validation didn’t prevent values out of their associated column data type range from being saved resulting in an integrity error.
  • - It is now possible to explicitly order_by() a relation _id field by using its attribute name.
  • Signals

  • - The model signals can be now be connected to using a str of the 'app_label.ModelName' form – just like related fields – to lazily reference their senders.
  • Templates

  • - The Context.push() method now returns a context manager which automatically calls pop() upon exiting the withstatement. Additionally, push() now accepts parameters that are passed to the dict constructor used to build the new context level.
  • - The new Context.flatten() method returns a Context‘s stack as one flat dictionary.
  • - Context objects can now be compared for equality (internally, this uses Context.flatten() so the internal structure of eachContext‘s stack doesn’t matter as long as their flattened version is identical).
  • - The widthratio template tag now accepts an "as" parameter to capture the result in a variable.
  • - The include template tag will now also accept anything with a render() method (such as a Template) as an argument. String arguments will be looked up using get_template() as always.
  • - It is now possible to include templates recursively.
  • - Template objects now have an origin attribute set when TEMPLATE_DEBUG is True. This allows template origins to be inspected and logged outside of the django.template infrastructure.
  • - TypeError exceptions are no longer silenced when raised during the rendering of a template.
  • - The following functions now accept a dirs parameter which is a list or tuple to override TEMPLATE_DIRS:
  • - 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 optional using 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.
  • Requests and Responses

  • - The new HttpRequest.scheme attribute specifies the scheme of the request (http or https normally).
  • - The shortcut redirect() now supports relative URLs.
  • Tests

  • - The 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.
  • - The 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.
  • - The database settings for testing have been collected into a dictionary named TEST.
  • Utilities

  • - Improved strip_tags() accuracy (but it still cannot guarantee an HTML-safe result, as stated in the documentation).
  • Validators

  • - 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.
  • Backwards incompatible changes in 1.7

  • Warning
  • 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 inmodel._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 Troubleshooting for solutions to some problems you may encounter.
  • Standalone scripts

  • If you’re using Django in a plain Python script — rather than a management command — and you rely on theDJANGO_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.
  • 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.
  • You should make sure that:
  • - 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

  • 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 raises LookupError instead of returning None when no model is found.
  • - The only_installed argument of get_model and get_models no longer exists, nor does the seed_cache argument ofget_model.
  • Management commands and order of 

  • 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

  • ValidationError 생성자와 내부 스토리지

  • The behavior of the ValidationError constructor has changed when it receives a container of errors as an argument (e.g. a listor 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 ofupdate_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
0 Comments