From 7462a78c1bdef2f37ea9aae5ad05170dbd14b34a Mon Sep 17 00:00:00 2001 From: Loic Bistuer Date: Thu, 20 Jun 2013 03:09:40 +0700 Subject: Fixed #20288 -- Fixed inconsistency in the naming of the popup GET parameter. Thanks to Keryn Knight for the initial report and reviews, and to tomask for the original patch. --- docs/releases/1.6.txt | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'docs') diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index bd6255eae6..16e0b94a9d 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -725,6 +725,12 @@ Miscellaneous returned ``False`` for blank passwords. This has been corrected in this release: blank passwords are now valid. +* The admin :attr:`~django.contrib.admin.ModelAdmin.changelist_view` previously + accepted a ``pop`` GET parameter to signify it was to be displayed in a popup. + This parameter has been renamed to ``_popup`` to be consistent with the rest + of the admin views. You should update your custom templates if they use the + previous parameter name. + Features deprecated in 1.6 ========================== -- cgit v1.3 From df4a74d7097f15cc271fee1c797dee3b96755066 Mon Sep 17 00:00:00 2001 From: Harm Geerts Date: Thu, 20 Jun 2013 03:02:25 +0200 Subject: Modified tutorial 3 to use RequestContext in place of Context. --- docs/intro/tutorial03.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/docs/intro/tutorial03.txt b/docs/intro/tutorial03.txt index 6193ec45f7..d9f3f50a0d 100644 --- a/docs/intro/tutorial03.txt +++ b/docs/intro/tutorial03.txt @@ -339,14 +339,14 @@ Put the following code in that template: Now let's update our ``index`` view in ``polls/views.py`` to use the template:: from django.http import HttpResponse - from django.template import Context, loader + from django.template import RequestContext, loader from polls.models import Poll def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') - context = Context({ + context = RequestContext({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(template.render(context)) @@ -377,7 +377,7 @@ rewritten:: return render(request, 'polls/index.html', context) Note that once we've done this in all these views, we no longer need to import -:mod:`~django.template.loader`, :class:`~django.template.Context` and +:mod:`~django.template.loader`, :class:`~django.template.RequestContext` and :class:`~django.http.HttpResponse` (you'll want to keep ``HttpResponse`` if you still have the stub methods for ``detail``, ``results``, and ``vote``). -- cgit v1.3 From 6ef199a08e1c452289deda67629b1630d25ccfcf Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Thu, 20 Jun 2013 10:41:29 -0400 Subject: Fixed error in last commit. Thanks Simon Charette. --- docs/intro/tutorial03.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/intro/tutorial03.txt b/docs/intro/tutorial03.txt index d9f3f50a0d..91409848cf 100644 --- a/docs/intro/tutorial03.txt +++ b/docs/intro/tutorial03.txt @@ -346,7 +346,7 @@ Now let's update our ``index`` view in ``polls/views.py`` to use the template:: def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') - context = RequestContext({ + context = RequestContext(request, { 'latest_poll_list': latest_poll_list, }) return HttpResponse(template.render(context)) -- cgit v1.3 From 7314007c5bf57b9184c0bd6a8246582dd2cb8179 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Thu, 20 Jun 2013 13:34:02 -0400 Subject: Fixed #19319 -- Updated example httpd.conf for Apache 2.4 Thanks colinnkeenan@ for the report. --- docs/howto/deployment/wsgi/modwsgi.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/howto/deployment/wsgi/modwsgi.txt b/docs/howto/deployment/wsgi/modwsgi.txt index 7749192358..2cbcd8ce7e 100644 --- a/docs/howto/deployment/wsgi/modwsgi.txt +++ b/docs/howto/deployment/wsgi/modwsgi.txt @@ -25,7 +25,8 @@ Basic configuration =================== Once you've got mod_wsgi installed and activated, edit your Apache server's -``httpd.conf`` file and add +``httpd.conf`` file and add the following. If you are using a version of Apache +older than 2.4, replace ``Require all granted`` with ``Allow from all``. .. code-block:: apache @@ -35,7 +36,7 @@ Once you've got mod_wsgi installed and activated, edit your Apache server's Order deny,allow - Allow from all + Require all granted -- cgit v1.3 From b53ed5ac55d5881f129c4921199af355e2b13565 Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Fri, 21 Jun 2013 17:46:10 +0200 Subject: Fixed #20612 -- Fixed incorrect wording in CBV documentation Thanks to ndokos for the report. --- docs/topics/class-based-views/generic-display.txt | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) (limited to 'docs') diff --git a/docs/topics/class-based-views/generic-display.txt b/docs/topics/class-based-views/generic-display.txt index 7ffa471e79..7a0d6df8c0 100644 --- a/docs/topics/class-based-views/generic-display.txt +++ b/docs/topics/class-based-views/generic-display.txt @@ -198,15 +198,12 @@ provided by the generic view. For example, think of showing a list of all the books on each publisher detail page. The :class:`~django.views.generic.detail.DetailView` generic view provides the publisher to the context, but how do we get additional information -in that template. - -However, there is; you can subclass -:class:`~django.views.generic.detail.DetailView` and provide your own -implementation of the ``get_context_data`` method. The default -implementation of this that comes with -:class:`~django.views.generic.detail.DetailView` simply adds in the -object being displayed to the template, but you can override it to send -more:: +in that template? + +The answer is to subclass :class:`~django.views.generic.detail.DetailView` +and provide your own implementation of the ``get_context_data`` method. +The default implementation simply adds the object being displayed to the +template, but you can override it to send more:: from django.views.generic import DetailView from books.models import Publisher, Book -- cgit v1.3 From ba610cb319d8882a663effcaf0a4e53c04593f98 Mon Sep 17 00:00:00 2001 From: James Bennett Date: Thu, 20 Jun 2013 01:36:13 -0500 Subject: Fixed #19881 -- Documented that get_next/previous_by_FOO uses default manager. --- docs/ref/models/instances.txt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt index cfc95db092..17c9aa9fb7 100644 --- a/docs/ref/models/instances.txt +++ b/docs/ref/models/instances.txt @@ -679,8 +679,11 @@ For every :class:`~django.db.models.DateField` and returns the next and previous object with respect to the date field, raising a :exc:`~django.core.exceptions.DoesNotExist` exception when appropriate. -Both methods accept optional keyword arguments, which should be in the format -described in :ref:`Field lookups `. +Both of these methods will perform their queries using the default +manager for the model. If you need to emulate filtering used by a +custom manager, or want to perform one-off custom filtering, both +methods also accept optional keyword arguments, which should be in the +format described in :ref:`Field lookups `. Note that in the case of identical date values, these methods will use the primary key as a tie-breaker. This guarantees that no records are skipped or -- cgit v1.3 From 9be93aa809c34083ebef8392e52c83df0e383be3 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Fri, 21 Jun 2013 14:55:59 -0400 Subject: Fixed #20634 - Corrected doc mistake re: staticfiles finders strategy. Thanks claudep for the catch and bmispelon for the research. --- docs/howto/static-files/index.txt | 2 +- docs/ref/settings.txt | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/howto/static-files/index.txt b/docs/howto/static-files/index.txt index 3668c5dc41..db8bd38e9c 100644 --- a/docs/howto/static-files/index.txt +++ b/docs/howto/static-files/index.txt @@ -68,7 +68,7 @@ details on how ``staticfiles`` finds your files. Now we *might* be able to get away with putting our static files directly in ``my_app/static/`` (rather than creating another ``my_app`` subdirectory), but it would actually be a bad idea. Django will use the - last static file it finds whose name matches, and if you had a static file + first static file it finds whose name matches, and if you had a static file with the same name in a *different* application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by *namespacing* them. That is, diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index 897af275a0..902eefa86a 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -2564,7 +2564,9 @@ various locations. The default will find files stored in the :setting:`STATICFILES_DIRS` setting (using ``django.contrib.staticfiles.finders.FileSystemFinder``) and in a ``static`` subdirectory of each app (using -``django.contrib.staticfiles.finders.AppDirectoriesFinder``) +``django.contrib.staticfiles.finders.AppDirectoriesFinder``). If multiple +files with the same name are present, the first file that is found will be +used. One finder is disabled by default: ``django.contrib.staticfiles.finders.DefaultStorageFinder``. If added to -- cgit v1.3 From ef37b23050637da643b47b1ee744702d4d603f4c Mon Sep 17 00:00:00 2001 From: Gilberto Gonçalves Date: Sat, 22 Jun 2013 12:12:43 +0100 Subject: Fixed #18872 -- Added prefix to FormMixin Thanks @ibustama for the initial patch and dragonsnaker for opening the report. --- AUTHORS | 1 + django/views/generic/edit.py | 13 ++++++++++++- docs/ref/class-based-views/mixins-editing.txt | 4 ++++ docs/releases/1.6.txt | 3 +++ tests/generic_views/test_edit.py | 21 ++++++++++++++++++++- 5 files changed, 40 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/AUTHORS b/AUTHORS index 3eb0a68be9..e4803dbe9a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -249,6 +249,7 @@ answer newbie questions, and generally made Django that much better: martin.glueck@gmail.com Ben Godfrey GomoX + Gil Gonçalves Guilherme Mesquita Gondim Mario Gonzalez David Gouldin diff --git a/django/views/generic/edit.py b/django/views/generic/edit.py index b31d7a218f..193071efc5 100644 --- a/django/views/generic/edit.py +++ b/django/views/generic/edit.py @@ -17,6 +17,7 @@ class FormMixin(ContextMixin): initial = {} form_class = None success_url = None + prefix = None def get_initial(self): """ @@ -24,6 +25,12 @@ class FormMixin(ContextMixin): """ return self.initial.copy() + def get_prefix(self): + """ + Returns the prefix to use for forms on this view + """ + return self.prefix + def get_form_class(self): """ Returns the form class to use in this view @@ -40,7 +47,11 @@ class FormMixin(ContextMixin): """ Returns the keyword arguments for instantiating the form. """ - kwargs = {'initial': self.get_initial()} + kwargs = { + 'initial': self.get_initial(), + 'prefix': self.get_prefix(), + } + if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, diff --git a/docs/ref/class-based-views/mixins-editing.txt b/docs/ref/class-based-views/mixins-editing.txt index 48d363b3b2..a0160610d2 100644 --- a/docs/ref/class-based-views/mixins-editing.txt +++ b/docs/ref/class-based-views/mixins-editing.txt @@ -35,6 +35,10 @@ FormMixin The URL to redirect to when the form is successfully processed. + .. attribute:: prefix + + Sets the :attr:`~django.forms.Form.prefix` for the generated form. + .. method:: get_initial() Retrieve initial data for the form. By default, returns a copy of diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 16e0b94a9d..95bfedc74e 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -731,6 +731,9 @@ Miscellaneous of the admin views. You should update your custom templates if they use the previous parameter name. +* Added :attr:`~django.views.generic.edit.FormMixin.prefix` to allow you to + customize the prefix on the form. + Features deprecated in 1.6 ========================== diff --git a/tests/generic_views/test_edit.py b/tests/generic_views/test_edit.py index 435e48ba99..84d18ebcb2 100644 --- a/tests/generic_views/test_edit.py +++ b/tests/generic_views/test_edit.py @@ -7,8 +7,9 @@ from django.core.urlresolvers import reverse from django import forms from django.test import TestCase from django.utils.unittest import expectedFailure +from django.test.client import RequestFactory from django.views.generic.base import View -from django.views.generic.edit import FormMixin, CreateView, UpdateView +from django.views.generic.edit import FormMixin, CreateView from . import views from .models import Artist, Author @@ -22,6 +23,24 @@ class FormMixinTests(TestCase): initial_2 = FormMixin().get_initial() self.assertNotEqual(initial_1, initial_2) + def test_get_prefix(self): + """ Test prefix can be set (see #18872) """ + test_string = 'test' + + rf = RequestFactory() + get_request = rf.get('/') + + class TestFormMixin(FormMixin): + request = get_request + + default_kwargs = TestFormMixin().get_form_kwargs() + self.assertEqual(None, default_kwargs.get('prefix')) + + set_mixin = TestFormMixin() + set_mixin.prefix = test_string + set_kwargs = set_mixin.get_form_kwargs() + self.assertEqual(test_string, set_kwargs.get('prefix')) + class BasicFormTests(TestCase): urls = 'generic_views.urls' -- cgit v1.3 From ecf63d5d89c5b511a023a4dcc32a142e1eed97e6 Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Sat, 22 Jun 2013 16:49:24 -0400 Subject: Added missing `versionadded` for `FormMixin.prefix`. --- docs/ref/class-based-views/mixins-editing.txt | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs') diff --git a/docs/ref/class-based-views/mixins-editing.txt b/docs/ref/class-based-views/mixins-editing.txt index a0160610d2..23b781c2e4 100644 --- a/docs/ref/class-based-views/mixins-editing.txt +++ b/docs/ref/class-based-views/mixins-editing.txt @@ -37,6 +37,8 @@ FormMixin .. attribute:: prefix + .. versionadded:: 1.6 + Sets the :attr:`~django.forms.Form.prefix` for the generated form. .. method:: get_initial() -- cgit v1.3 From bd9fbd1497edc585c5bec28c7d4bc8d1afd1943b Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Sat, 22 Jun 2013 23:05:22 +0200 Subject: Fixed errors and inconsistencies in CBV topic documentation. The code examples should now work correctly. The `get_context_data` method in the examples was changed when necessary to adopt a singular style (get context with super(...), add the extra keys to the dict then return it). Thanks to Remco Wendt for the initial report and to Tim Graham for the review. --- docs/topics/class-based-views/generic-display.txt | 25 ++++-- docs/topics/class-based-views/generic-editing.txt | 5 +- docs/topics/class-based-views/intro.txt | 2 +- docs/topics/class-based-views/mixins.txt | 102 ++++++++++------------ 4 files changed, 66 insertions(+), 68 deletions(-) (limited to 'docs') diff --git a/docs/topics/class-based-views/generic-display.txt b/docs/topics/class-based-views/generic-display.txt index 7a0d6df8c0..8c2d0db041 100644 --- a/docs/topics/class-based-views/generic-display.txt +++ b/docs/topics/class-based-views/generic-display.txt @@ -92,6 +92,15 @@ We'll be using these models:: def __unicode__(self): return self.name + class Author(models.Model): + salutation = models.CharField(max_length=10) + name = models.CharField(max_length=200) + email = models.EmailField() + headshot = models.ImageField(upload_to='author_headshots') + + def __unicode__(self): + return self.name + class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author') @@ -132,11 +141,11 @@ bit is just the lowercased version of the model's name. enabled in :setting:`TEMPLATE_LOADERS`, a template location could be: /path/to/project/books/templates/books/publisher_list.html -.. highlightlang:: html+django - This template will be rendered against a context containing a variable called ``object_list`` that contains all the publisher objects. A very simple template -might look like the following:: +might look like the following: + +.. code-block:: html+django {% extends "base.html" %} @@ -159,8 +168,6 @@ consider some of the common ways you might customize and extend generic views. Making "friendly" template contexts ----------------------------------- -.. highlightlang:: python - You might have noticed that our sample publisher list template stores all the publishers in a variable named ``object_list``. While this works just fine, it isn't all that "friendly" to template authors: they have to "just know" that @@ -221,10 +228,10 @@ template, but you can override it to send more:: .. note:: - Generally, get_context_data will merge the context data of all parent + Generally, ``get_context_data`` will merge the context data of all parent classes with those of the current class. To preserve this behavior in your own classes where you want to alter the context, you should be sure to call - get_context_data on the super class. When no two classes try to define the + ``get_context_data`` on the super class. When no two classes try to define the same key, this will give the expected results. However if any class attempts to override a key after parent classes have set it (after the call to super), any children of that class will also need to explicitly set it @@ -369,7 +376,7 @@ Performing extra work The last common pattern we'll look at involves doing some extra work before or after calling the generic view. -Imagine we had a ``last_accessed`` field on our ``Author`` object that we were +Imagine we had a ``last_accessed`` field on our ``Author`` model that we were using to keep track of the last time anybody looked at that author:: # models.py @@ -379,7 +386,7 @@ using to keep track of the last time anybody looked at that author:: salutation = models.CharField(max_length=10) name = models.CharField(max_length=200) email = models.EmailField() - headshot = models.ImageField(upload_to='/tmp') + headshot = models.ImageField(upload_to='author_headshots') last_accessed = models.DateTimeField() The generic ``DetailView`` class, of course, wouldn't know anything about this diff --git a/docs/topics/class-based-views/generic-editing.txt b/docs/topics/class-based-views/generic-editing.txt index 7c4e02cc4e..f12672df69 100644 --- a/docs/topics/class-based-views/generic-editing.txt +++ b/docs/topics/class-based-views/generic-editing.txt @@ -190,8 +190,8 @@ the foreign key relation to the model:: # ... -In the view, ensure that you exclude ``created_by`` in the list of fields to -edit, and override +In the view, ensure that you don't include ``created_by`` in the list of fields +to edit, and override :meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` to add the user:: # views.py @@ -256,3 +256,4 @@ works for AJAX requests as well as 'normal' form POSTs:: class AuthorCreate(AjaxableResponseMixin, CreateView): model = Author + fields = ['name'] diff --git a/docs/topics/class-based-views/intro.txt b/docs/topics/class-based-views/intro.txt index dbbbea25f0..a65b887921 100644 --- a/docs/topics/class-based-views/intro.txt +++ b/docs/topics/class-based-views/intro.txt @@ -208,7 +208,7 @@ A similar class-based view might look like:: def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) - return render(request, self.template_name, {'form': form}) + return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) diff --git a/docs/topics/class-based-views/mixins.txt b/docs/topics/class-based-views/mixins.txt index 3a4811e7bb..f13c468d5a 100644 --- a/docs/topics/class-based-views/mixins.txt +++ b/docs/topics/class-based-views/mixins.txt @@ -286,12 +286,17 @@ One way to do this is to combine :class:`ListView` with for the paginated list of books can hang off the publisher found as the single object. In order to do this, we need to have two different querysets: -**Publisher queryset for use in get_object** - We'll set that up directly when we call ``get_object()``. - -**Book queryset for use by ListView** - We'll figure that out ourselves in ``get_queryset()`` so we - can take into account the ``Publisher`` we're looking at. +**``Publisher`` queryset for use in ``get_object``** + We'll set the ``model`` attribute on the view and rely on the default + implementation of ``get_object()`` to fetch the correct ``Publisher`` + object. + +**``Book`` queryset for use by ``ListView``** + The default implementation of ``get_queryset`` uses the ``model`` attribute + to construct the queryset. This conflicts with our use of this attribute + for ``get_object`` so we'll override that method and have it return + the queryset of ``Book`` objects linked to the ``Publisher`` we're looking + at. .. note:: @@ -300,7 +305,7 @@ object. In order to do this, we need to have two different querysets: :class:`ListView` will put things in the context data under the value of ``context_object_name`` if it's set, we'll instead explictly - ensure the Publisher is in the context data. :class:`ListView` + ensure the ``Publisher`` is in the context data. :class:`ListView` will add in the suitable ``page_obj`` and ``paginator`` for us providing we remember to call ``super()``. @@ -311,31 +316,36 @@ Now we can write a new ``PublisherDetail``:: from books.models import Publisher class PublisherDetail(SingleObjectMixin, ListView): + model = Publisher # for SingleObjectMixin.get_object paginate_by = 2 template_name = "books/publisher_detail.html" + def get(self, request, *args, **kwargs): + self.object = self.get_object() + return super(PublisherDetail, self).get(request, *args, **kwargs) + def get_context_data(self, **kwargs): - kwargs['publisher'] = self.object - return super(PublisherDetail, self).get_context_data(**kwargs) + context = super(PublisherDetail, self).get_context_data(**kwargs) + context['publisher'] = self.object + return context def get_queryset(self): - self.object = self.get_object(Publisher.objects.all()) return self.object.book_set.all() -Notice how we set ``self.object`` within ``get_queryset()`` so we -can use it again later in ``get_context_data()``. If you don't set -``template_name``, the template will default to the normal +Notice how we set ``self.object`` within ``get()`` so we +can use it again later in ``get_context_data()`` and ``get_queryset()``. +If you don't set ``template_name``, the template will default to the normal :class:`ListView` choice, which in this case would be ``"books/book_list.html"`` because it's a list of books; :class:`ListView` knows nothing about :class:`~django.views.generic.detail.SingleObjectMixin`, so it doesn't have -any clue this view is anything to do with a Publisher. - -.. highlightlang:: html+django +any clue this view is anything to do with a ``Publisher``. The ``paginate_by`` is deliberately small in the example so you don't have to create lots of books to see the pagination working! Here's the -template you'd want to use:: +template you'd want to use: + +.. code-block: html+django {% extends "base.html" %} @@ -427,8 +437,6 @@ code so that on ``POST`` the form gets called appropriately. both of the views implement ``get()``, and things would get much more confusing. -.. highlightlang:: python - Our new ``AuthorDetail`` looks like this:: # CAUTION: you almost certainly do not want to do this. @@ -451,21 +459,18 @@ Our new ``AuthorDetail`` looks like this:: form_class = AuthorInterestForm def get_success_url(self): - return reverse( - 'author-detail', - kwargs = {'pk': self.object.pk}, - ) + return reverse('author-detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): + context = super(AuthorDetail, self).get_context_data(**kwargs) form_class = self.get_form_class() - form = self.get_form(form_class) - context = { - 'form': form - } - context.update(kwargs) - return super(AuthorDetail, self).get_context_data(**context) + context['form'] = self.get_form(form_class) + return context def post(self, request, *args, **kwargs): + if not request.user.is_authenticated(): + return HttpResponseForbidden() + self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): @@ -474,10 +479,8 @@ Our new ``AuthorDetail`` looks like this:: return self.form_invalid(form) def form_valid(self, form): - if not self.request.user.is_authenticated(): - return HttpResponseForbidden() - self.object = self.get_object() - # record the interest using the message in form.cleaned_data + # Here, we would record the user's interest using the message + # passed in form.cleaned_data['message'] return super(AuthorDetail, self).form_valid(form) ``get_success_url()`` is just providing somewhere to redirect to, @@ -530,15 +533,12 @@ write our own ``get_context_data()`` to make the message = forms.CharField() class AuthorDisplay(DetailView): - - queryset = Author.objects.all() + model = Author def get_context_data(self, **kwargs): - context = { - 'form': AuthorInterestForm(), - } - context.update(kwargs) - return super(AuthorDisplay, self).get_context_data(**context) + context = super(AuthorDisplay, self).get_context_data(**kwargs) + context['form'] = AuthorInterestForm() + return context Then the ``AuthorInterest`` is a simple :class:`FormView`, but we have to bring in :class:`~django.views.generic.detail.SingleObjectMixin` so we @@ -558,24 +558,14 @@ template as ``AuthorDisplay`` is using on ``GET``. form_class = AuthorInterestForm model = Author - def get_context_data(self, **kwargs): - context = { - 'object': self.get_object(), - } - return super(AuthorInterest, self).get_context_data(**context) - - def get_success_url(self): - return reverse( - 'author-detail', - kwargs = {'pk': self.object.pk}, - ) - - def form_valid(self, form): - if not self.request.user.is_authenticated(): + def post(self, request, *args, **kwargs): + if not request.user.is_authenticated(): return HttpResponseForbidden() self.object = self.get_object() - # record the interest using the message in form.cleaned_data - return super(AuthorInterest, self).form_valid(form) + return super(AuthorInterest, self).post(request, *args, **kwargs) + + def get_success_url(self): + return reverse('author-detail', kwargs={'pk': self.object.pk}) Finally we bring this together in a new ``AuthorDetail`` view. We already know that calling :meth:`~django.views.generic.base.View.as_view()` on -- cgit v1.3 From b0907d66a5ac7bdc5585cbebc56acf21274f2709 Mon Sep 17 00:00:00 2001 From: SusanTan Date: Sat, 22 Jun 2013 16:30:44 -0400 Subject: Fixed #20524 - Described keywords in triaging contrib doc. --- docs/internals/contributing/triaging-tickets.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/internals/contributing/triaging-tickets.txt b/docs/internals/contributing/triaging-tickets.txt index 43b799ed51..7bb59bc329 100644 --- a/docs/internals/contributing/triaging-tickets.txt +++ b/docs/internals/contributing/triaging-tickets.txt @@ -255,7 +255,11 @@ Keywords ~~~~~~~~ With this field you may label a ticket with multiple keywords. This can be -useful, for example, to group several tickets of a same theme. +useful, for example, to group several tickets of a same theme. Keywords can +either be comma or space separated. Keyword search finds the keyword string +anywhere in the keywords. For example, clicking on a ticket with the keyword +"form" will yield similar tickets tagged with keywords containing strings such +as "formset", "modelformset", and "ManagementForm". .. _closing-tickets: -- cgit v1.3 From 6466a0837b741e72a7aa55b4e28e132a48b82d85 Mon Sep 17 00:00:00 2001 From: Simon Meers Date: Mon, 24 Jun 2013 13:59:03 +1000 Subject: Corrected minor typos in FileUploadHandler.receive_data_chunk docs. --- docs/topics/http/file-uploads.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt index 54d748d961..f6fa27e27c 100644 --- a/docs/topics/http/file-uploads.txt +++ b/docs/topics/http/file-uploads.txt @@ -371,8 +371,8 @@ Custom file upload handlers **must** define the following methods: ``receive_data_chunk`` methods. In this way, one handler can be a "filter" for other handlers. - Return ``None`` from ``receive_data_chunk`` to sort-circuit remaining - upload handlers from getting this chunk.. This is useful if you're + Return ``None`` from ``receive_data_chunk`` to short-circuit remaining + upload handlers from getting this chunk. This is useful if you're storing the uploaded data yourself and don't want future handlers to store a copy of the data. -- cgit v1.3 From cd000dacc7cef8e55793d19242d0df0f3e736949 Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Mon, 24 Jun 2013 11:55:43 +0200 Subject: Fixed #20643 -- Fixed implementation of JSONResponseMixin in CBV docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks to Michal Sládek for the report and initial patch, and to loic84 for the review. --- docs/topics/class-based-views/mixins.txt | 44 ++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 17 deletions(-) (limited to 'docs') diff --git a/docs/topics/class-based-views/mixins.txt b/docs/topics/class-based-views/mixins.txt index f13c468d5a..b6552b9108 100644 --- a/docs/topics/class-based-views/mixins.txt +++ b/docs/topics/class-based-views/mixins.txt @@ -617,15 +617,13 @@ For example, a simple JSON mixin might look something like this:: """ A mixin that can be used to render a JSON response. """ - response_class = HttpResponse - - def render_to_response(self, context, **response_kwargs): + def render_to_json_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ - response_kwargs['content_type'] = 'application/json' - return self.response_class( + return HttpResponse( self.convert_context_to_json(context), + content_type='application/json', **response_kwargs ) @@ -637,12 +635,22 @@ For example, a simple JSON mixin might look something like this:: # -- can be serialized as JSON. return json.dumps(context) -Now we mix this into the base TemplateView:: +.. note:: + + Check out the :doc:`/topics/serialization` documentation for more + information on how to correctly transform Django models and querysets into + JSON. + +This mixin provides a ``render_to_json_response`` method with the same signature +as :func:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`. +To use it, we simply need to mix it into a ``TemplateView`` for example, +and override ``render_to_response`` to call ``render_to_json_response`` instead:: from django.views.generic import TemplateView class JSONView(JSONResponseMixin, TemplateView): - pass + def render_to_response(self, context, **response_kwargs): + return self.render_to_json_response(context, **response_kwargs) Equally we could use our mixin with one of the generic views. We can make our own version of :class:`~django.views.generic.detail.DetailView` by mixing @@ -654,7 +662,8 @@ rendering behavior has been mixed in):: from django.views.generic.detail import BaseDetailView class JSONDetailView(JSONResponseMixin, BaseDetailView): - pass + def render_to_response(self, context, **response_kwargs): + return self.render_to_json_response(context, **response_kwargs) This view can then be deployed in the same way as any other :class:`~django.views.generic.detail.DetailView`, with exactly the @@ -668,20 +677,21 @@ in both the ``JSONResponseMixin`` and a :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`, and override the implementation of :func:`~django.views.generic.base.TemplateResponseMixin.render_to_response()` -to defer to the appropriate subclass depending on the type of response that the -user requested:: +to defer to the appropriate rendering method depending on the type of response +that the user requested:: from django.views.generic.detail import SingleObjectTemplateResponseMixin class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView): def render_to_response(self, context): # Look for a 'format=json' GET argument - if self.request.GET.get('format','html') == 'json': - return JSONResponseMixin.render_to_response(self, context) + if self.request.GET.get('format') == 'json': + return self.render_to_json_response(context) else: - return SingleObjectTemplateResponseMixin.render_to_response(self, context) + return super(HybridDetailView, self).render_to_response(context) -Because of the way that Python resolves method overloading, the local -``render_to_response()`` implementation will override the versions provided by -``JSONResponseMixin`` and -:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`. +Because of the way that Python resolves method overloading, the call to +``super(HybridDetailView, self).render_to_response(context)`` ends up +calling the +:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response` +implementation of :class:`~django.views.generic.base.TemplateResponseMixin`. -- cgit v1.3 From 299983616ffc146a6f5aa03af9b3f4a56853f05c Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Sun, 23 Jun 2013 23:43:09 +0200 Subject: Fixed #20644 -- Add ModelFormMixin.fields to the CBV flattened index Thanks to Tim Graham for the report and review. --- django/views/generic/edit.py | 6 +++--- docs/ref/class-based-views/flattened-index.txt | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/django/views/generic/edit.py b/django/views/generic/edit.py index 193071efc5..fccacf0bd3 100644 --- a/django/views/generic/edit.py +++ b/django/views/generic/edit.py @@ -89,6 +89,7 @@ class ModelFormMixin(FormMixin, SingleObjectMixin): """ A mixin that provides a way to show and handle a modelform in a request. """ + fields = None def get_form_class(self): """ @@ -109,13 +110,12 @@ class ModelFormMixin(FormMixin, SingleObjectMixin): # from that model = self.get_queryset().model - fields = getattr(self, 'fields', None) - if fields is None: + if self.fields is None: warnings.warn("Using ModelFormMixin (base class of %s) without " "the 'fields' attribute is deprecated." % self.__class__.__name__, PendingDeprecationWarning) - return model_forms.modelform_factory(model, fields=fields) + return model_forms.modelform_factory(model, fields=self.fields) def get_form_kwargs(self): """ diff --git a/docs/ref/class-based-views/flattened-index.txt b/docs/ref/class-based-views/flattened-index.txt index df00f87aa0..7634a07300 100644 --- a/docs/ref/class-based-views/flattened-index.txt +++ b/docs/ref/class-based-views/flattened-index.txt @@ -177,6 +177,7 @@ CreateView * :attr:`~django.views.generic.base.TemplateResponseMixin.content_type` * :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`] +* :attr:`~django.views.generic.edit.ModelFormMixin.fields` * :attr:`~django.views.generic.edit.FormMixin.form_class` [:meth:`~django.views.generic.edit.FormMixin.get_form_class`] * :attr:`~django.views.generic.base.View.http_method_names` * :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`] @@ -216,6 +217,7 @@ UpdateView * :attr:`~django.views.generic.base.TemplateResponseMixin.content_type` * :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`] +* :attr:`~django.views.generic.edit.ModelFormMixin.fields` * :attr:`~django.views.generic.edit.FormMixin.form_class` [:meth:`~django.views.generic.edit.FormMixin.get_form_class`] * :attr:`~django.views.generic.base.View.http_method_names` * :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`] -- cgit v1.3 From e161e4ff1176acb1b3636e3f93280055185d3d78 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Mon, 24 Jun 2013 07:00:53 -0400 Subject: Clarified get_list_or_404 docs, refs #14150. --- docs/topics/http/shortcuts.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt index 52a2935977..5c8725172a 100644 --- a/docs/topics/http/shortcuts.txt +++ b/docs/topics/http/shortcuts.txt @@ -277,8 +277,8 @@ will be raised if more than one object is found. .. function:: get_list_or_404(klass, *args, **kwargs) Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on a - given model manager, raising :class:`~django.http.Http404` if the resulting - list is empty. + given model manager cast to a list, raising :class:`~django.http.Http404` if + the resulting list is empty. Required arguments ------------------ -- cgit v1.3 From 0346563939396fb89dec8df31f82eaefaaeb8616 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Tue, 25 Jun 2013 09:37:54 +0800 Subject: Fixed #20653 -- Renamed checksetup management command. This is to allow future compatibility with work that is ongoing in the 2013 GSoC. --- django/core/checks/__init__.py | 0 django/core/checks/compatibility/__init__.py | 0 django/core/checks/compatibility/base.py | 39 +++++++++ django/core/checks/compatibility/django_1_6_0.py | 37 ++++++++ django/core/compat_checks/__init__.py | 0 django/core/compat_checks/base.py | 39 --------- django/core/compat_checks/django_1_6_0.py | 37 -------- django/core/management/commands/check.py | 14 +++ django/core/management/commands/checksetup.py | 14 --- docs/releases/1.6.txt | 6 +- tests/check/__init__.py | 0 tests/check/models.py | 1 + tests/check/tests.py | 107 +++++++++++++++++++++++ tests/compat_checks/__init__.py | 0 tests/compat_checks/models.py | 1 - tests/compat_checks/tests.py | 107 ----------------------- 16 files changed, 201 insertions(+), 201 deletions(-) create mode 100644 django/core/checks/__init__.py create mode 100644 django/core/checks/compatibility/__init__.py create mode 100644 django/core/checks/compatibility/base.py create mode 100644 django/core/checks/compatibility/django_1_6_0.py delete mode 100644 django/core/compat_checks/__init__.py delete mode 100644 django/core/compat_checks/base.py delete mode 100644 django/core/compat_checks/django_1_6_0.py create mode 100644 django/core/management/commands/check.py delete mode 100644 django/core/management/commands/checksetup.py create mode 100644 tests/check/__init__.py create mode 100644 tests/check/models.py create mode 100644 tests/check/tests.py delete mode 100644 tests/compat_checks/__init__.py delete mode 100644 tests/compat_checks/models.py delete mode 100644 tests/compat_checks/tests.py (limited to 'docs') diff --git a/django/core/checks/__init__.py b/django/core/checks/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/django/core/checks/compatibility/__init__.py b/django/core/checks/compatibility/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/django/core/checks/compatibility/base.py b/django/core/checks/compatibility/base.py new file mode 100644 index 0000000000..7fe52d2af9 --- /dev/null +++ b/django/core/checks/compatibility/base.py @@ -0,0 +1,39 @@ +from __future__ import unicode_literals +import warnings + +from django.core.checks.compatibility import django_1_6_0 + + +COMPAT_CHECKS = [ + # Add new modules at the top, so we keep things in descending order. + # After two-three minor releases, old versions should get dropped. + django_1_6_0, +] + + +def check_compatibility(): + """ + Runs through compatibility checks to warn the user with an existing install + about changes in an up-to-date Django. + + Modules should be located in ``django.core.compat_checks`` (typically one + per release of Django) & must have a ``run_checks`` function that runs + all the checks. + + Returns a list of informational messages about incompatibilities. + """ + messages = [] + + for check_module in COMPAT_CHECKS: + check = getattr(check_module, 'run_checks', None) + + if check is None: + warnings.warn( + "The '%s' module lacks a " % check_module.__name__ + + "'run_checks' method, which is needed to verify compatibility." + ) + continue + + messages.extend(check()) + + return messages diff --git a/django/core/checks/compatibility/django_1_6_0.py b/django/core/checks/compatibility/django_1_6_0.py new file mode 100644 index 0000000000..1998c5ba77 --- /dev/null +++ b/django/core/checks/compatibility/django_1_6_0.py @@ -0,0 +1,37 @@ +from __future__ import unicode_literals + + +def check_test_runner(): + """ + Checks if the user has *not* overridden the ``TEST_RUNNER`` setting & + warns them about the default behavior changes. + + If the user has overridden that setting, we presume they know what they're + doing & avoid generating a message. + """ + from django.conf import settings + new_default = 'django.test.runner.DiscoverRunner' + test_runner_setting = getattr(settings, 'TEST_RUNNER', new_default) + + if test_runner_setting == new_default: + message = [ + "You have not explicitly set 'TEST_RUNNER'. In Django 1.6,", + "there is a new test runner ('%s')" % new_default, + "by default. You should ensure your tests are still all", + "running & behaving as expected. See", + "https://docs.djangoproject.com/en/dev/releases/1.6/#discovery-of-tests-in-any-test-module", + "for more information.", + ] + return ' '.join(message) + + +def run_checks(): + """ + Required by the ``check`` management command, this returns a list of + messages from all the relevant check functions for this version of Django. + """ + checks = [ + check_test_runner() + ] + # Filter out the ``None`` or empty strings. + return [output for output in checks if output] diff --git a/django/core/compat_checks/__init__.py b/django/core/compat_checks/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/django/core/compat_checks/base.py b/django/core/compat_checks/base.py deleted file mode 100644 index e54b50f287..0000000000 --- a/django/core/compat_checks/base.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import unicode_literals -import warnings - -from django.core.compat_checks import django_1_6_0 - - -COMPAT_CHECKS = [ - # Add new modules at the top, so we keep things in descending order. - # After two-three minor releases, old versions should get dropped. - django_1_6_0, -] - - -def check_compatibility(): - """ - Runs through compatibility checks to warn the user with an existing install - about changes in an up-to-date Django. - - Modules should be located in ``django.core.compat_checks`` (typically one - per release of Django) & must have a ``run_checks`` function that runs - all the checks. - - Returns a list of informational messages about incompatibilities. - """ - messages = [] - - for check_module in COMPAT_CHECKS: - check = getattr(check_module, 'run_checks', None) - - if check is None: - warnings.warn( - "The '%s' module lacks a " % check_module.__name__ + - "'run_checks' method, which is needed to verify compatibility." - ) - continue - - messages.extend(check()) - - return messages diff --git a/django/core/compat_checks/django_1_6_0.py b/django/core/compat_checks/django_1_6_0.py deleted file mode 100644 index bb0dabedac..0000000000 --- a/django/core/compat_checks/django_1_6_0.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import unicode_literals - - -def check_test_runner(): - """ - Checks if the user has *not* overridden the ``TEST_RUNNER`` setting & - warns them about the default behavior changes. - - If the user has overridden that setting, we presume they know what they're - doing & avoid generating a message. - """ - from django.conf import settings - new_default = 'django.test.runner.DiscoverRunner' - test_runner_setting = getattr(settings, 'TEST_RUNNER', new_default) - - if test_runner_setting == new_default: - message = [ - "You have not explicitly set 'TEST_RUNNER'. In Django 1.6,", - "there is a new test runner ('%s')" % new_default, - "by default. You should ensure your tests are still all", - "running & behaving as expected. See", - "https://docs.djangoproject.com/en/dev/releases/1.6/#discovery-of-tests-in-any-test-module", - "for more information.", - ] - return ' '.join(message) - - -def run_checks(): - """ - Required by the ``checksetup`` management command, this returns a list of - messages from all the relevant check functions for this version of Django. - """ - checks = [ - check_test_runner() - ] - # Filter out the ``None`` or empty strings. - return [output for output in checks if output] diff --git a/django/core/management/commands/check.py b/django/core/management/commands/check.py new file mode 100644 index 0000000000..05f48c82bc --- /dev/null +++ b/django/core/management/commands/check.py @@ -0,0 +1,14 @@ +from __future__ import unicode_literals +import warnings + +from django.core.checks.compatibility.base import check_compatibility +from django.core.management.base import NoArgsCommand + + +class Command(NoArgsCommand): + help = "Checks your configuration's compatibility with this version " + \ + "of Django." + + def handle_noargs(self, **options): + for message in check_compatibility(): + warnings.warn(message) diff --git a/django/core/management/commands/checksetup.py b/django/core/management/commands/checksetup.py deleted file mode 100644 index d37e826757..0000000000 --- a/django/core/management/commands/checksetup.py +++ /dev/null @@ -1,14 +0,0 @@ -from __future__ import unicode_literals -import warnings - -from django.core.compat_checks.base import check_compatibility -from django.core.management.base import NoArgsCommand - - -class Command(NoArgsCommand): - help = "Checks your configuration's compatibility with this version " + \ - "of Django." - - def handle_noargs(self, **options): - for message in check_compatibility(): - warnings.warn(message) diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 95bfedc74e..086c10c389 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -121,10 +121,10 @@ GeoDjango now provides :ref:`form fields and widgets ` for its geo-specialized fields. They are OpenLayers-based by default, but they can be customized to use any other JS framework. -``checksetup`` management command added for verifying compatibility -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``check`` management command added for verifying compatibility +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A ``checksetup`` management command was added, enabling you to verify if your +A ``check`` management command was added, enabling you to verify if your current configuration (currently oriented at settings) is compatible with the current version of Django. diff --git a/tests/check/__init__.py b/tests/check/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/check/models.py b/tests/check/models.py new file mode 100644 index 0000000000..78a10abba6 --- /dev/null +++ b/tests/check/models.py @@ -0,0 +1 @@ +# Stubby. diff --git a/tests/check/tests.py b/tests/check/tests.py new file mode 100644 index 0000000000..98495e38ae --- /dev/null +++ b/tests/check/tests.py @@ -0,0 +1,107 @@ +from django.core.checks.compatibility import base +from django.core.checks.compatibility import django_1_6_0 +from django.core.management.commands import check +from django.core.management import call_command +from django.test import TestCase + + +class StubCheckModule(object): + # Has no ``run_checks`` attribute & will trigger a warning. + __name__ = 'StubCheckModule' + + +class FakeWarnings(object): + def __init__(self): + self._warnings = [] + + def warn(self, message): + self._warnings.append(message) + + +class CompatChecksTestCase(TestCase): + def setUp(self): + super(CompatChecksTestCase, self).setUp() + + # We're going to override the list of checks to perform for test + # consistency in the future. + self.old_compat_checks = base.COMPAT_CHECKS + base.COMPAT_CHECKS = [ + django_1_6_0, + ] + + def tearDown(self): + # Restore what's supposed to be in ``COMPAT_CHECKS``. + base.COMPAT_CHECKS = self.old_compat_checks + super(CompatChecksTestCase, self).tearDown() + + def test_check_test_runner_new_default(self): + with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): + result = django_1_6_0.check_test_runner() + self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in result) + + def test_check_test_runner_overridden(self): + with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): + self.assertEqual(django_1_6_0.check_test_runner(), None) + + def test_run_checks_new_default(self): + with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): + result = django_1_6_0.run_checks() + self.assertEqual(len(result), 1) + self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in result[0]) + + def test_run_checks_overridden(self): + with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): + self.assertEqual(len(django_1_6_0.run_checks()), 0) + + def test_check_compatibility(self): + with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): + result = base.check_compatibility() + self.assertEqual(len(result), 1) + self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in result[0]) + + with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): + self.assertEqual(len(base.check_compatibility()), 0) + + def test_check_compatibility_warning(self): + # First, we're patching over the ``COMPAT_CHECKS`` with a stub which + # will trigger the warning. + base.COMPAT_CHECKS = [ + StubCheckModule(), + ] + + # Next, we unfortunately have to patch out ``warnings``. + old_warnings = base.warnings + base.warnings = FakeWarnings() + + self.assertEqual(len(base.warnings._warnings), 0) + + with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): + self.assertEqual(len(base.check_compatibility()), 0) + + self.assertEqual(len(base.warnings._warnings), 1) + self.assertTrue("The 'StubCheckModule' module lacks a 'run_checks'" in base.warnings._warnings[0]) + + # Restore the ``warnings``. + base.warnings = old_warnings + + def test_management_command(self): + # Again, we unfortunately have to patch out ``warnings``. Different + old_warnings = check.warnings + check.warnings = FakeWarnings() + + self.assertEqual(len(check.warnings._warnings), 0) + + # Should not produce any warnings. + with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): + call_command('check') + + self.assertEqual(len(check.warnings._warnings), 0) + + with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): + call_command('check') + + self.assertEqual(len(check.warnings._warnings), 1) + self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in check.warnings._warnings[0]) + + # Restore the ``warnings``. + base.warnings = old_warnings diff --git a/tests/compat_checks/__init__.py b/tests/compat_checks/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/compat_checks/models.py b/tests/compat_checks/models.py deleted file mode 100644 index 78a10abba6..0000000000 --- a/tests/compat_checks/models.py +++ /dev/null @@ -1 +0,0 @@ -# Stubby. diff --git a/tests/compat_checks/tests.py b/tests/compat_checks/tests.py deleted file mode 100644 index 879988c905..0000000000 --- a/tests/compat_checks/tests.py +++ /dev/null @@ -1,107 +0,0 @@ -from django.core.compat_checks import base -from django.core.compat_checks import django_1_6_0 -from django.core.management.commands import checksetup -from django.core.management import call_command -from django.test import TestCase - - -class StubCheckModule(object): - # Has no ``run_checks`` attribute & will trigger a warning. - __name__ = 'StubCheckModule' - - -class FakeWarnings(object): - def __init__(self): - self._warnings = [] - - def warn(self, message): - self._warnings.append(message) - - -class CompatChecksTestCase(TestCase): - def setUp(self): - super(CompatChecksTestCase, self).setUp() - - # We're going to override the list of checks to perform for test - # consistency in the future. - self.old_compat_checks = base.COMPAT_CHECKS - base.COMPAT_CHECKS = [ - django_1_6_0, - ] - - def tearDown(self): - # Restore what's supposed to be in ``COMPAT_CHECKS``. - base.COMPAT_CHECKS = self.old_compat_checks - super(CompatChecksTestCase, self).tearDown() - - def test_check_test_runner_new_default(self): - with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): - result = django_1_6_0.check_test_runner() - self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in result) - - def test_check_test_runner_overridden(self): - with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): - self.assertEqual(django_1_6_0.check_test_runner(), None) - - def test_run_checks_new_default(self): - with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): - result = django_1_6_0.run_checks() - self.assertEqual(len(result), 1) - self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in result[0]) - - def test_run_checks_overridden(self): - with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): - self.assertEqual(len(django_1_6_0.run_checks()), 0) - - def test_check_compatibility(self): - with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): - result = base.check_compatibility() - self.assertEqual(len(result), 1) - self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in result[0]) - - with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): - self.assertEqual(len(base.check_compatibility()), 0) - - def test_check_compatibility_warning(self): - # First, we're patching over the ``COMPAT_CHECKS`` with a stub which - # will trigger the warning. - base.COMPAT_CHECKS = [ - StubCheckModule(), - ] - - # Next, we unfortunately have to patch out ``warnings``. - old_warnings = base.warnings - base.warnings = FakeWarnings() - - self.assertEqual(len(base.warnings._warnings), 0) - - with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): - self.assertEqual(len(base.check_compatibility()), 0) - - self.assertEqual(len(base.warnings._warnings), 1) - self.assertTrue("The 'StubCheckModule' module lacks a 'run_checks'" in base.warnings._warnings[0]) - - # Restore the ``warnings``. - base.warnings = old_warnings - - def test_management_command(self): - # Again, we unfortunately have to patch out ``warnings``. Different - old_warnings = checksetup.warnings - checksetup.warnings = FakeWarnings() - - self.assertEqual(len(checksetup.warnings._warnings), 0) - - # Should not produce any warnings. - with self.settings(TEST_RUNNER='myapp.test.CustomRunnner'): - call_command('checksetup') - - self.assertEqual(len(checksetup.warnings._warnings), 0) - - with self.settings(TEST_RUNNER='django.test.runner.DiscoverRunner'): - call_command('checksetup') - - self.assertEqual(len(checksetup.warnings._warnings), 1) - self.assertTrue("You have not explicitly set 'TEST_RUNNER'" in checksetup.warnings._warnings[0]) - - # Restore the ``warnings``. - base.warnings = old_warnings -- cgit v1.3 From 9a2b07f1b45741da39a7606474aec3548780032b Mon Sep 17 00:00:00 2001 From: Daniel Izquierdo Date: Tue, 25 Jun 2013 14:40:56 +0900 Subject: Fixed #20654 -- Fixed type of `m2m_changed`'s `pk_set` arg in docs --- docs/ref/signals.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/docs/ref/signals.txt b/docs/ref/signals.txt index 06ba2cb3e8..0fdfb0ee14 100644 --- a/docs/ref/signals.txt +++ b/docs/ref/signals.txt @@ -255,7 +255,7 @@ Arguments sent with this signal: ``pk_set`` For the ``pre_add``, ``post_add``, ``pre_remove`` and ``post_remove`` - actions, this is a list of primary key values that have been added to + actions, this is a set of primary key values that have been added to or removed from the relation. For the ``pre_clear`` and ``post_clear`` actions, this is ``None``. @@ -307,7 +307,7 @@ Argument Value ``model`` ``Topping`` (the class of the objects added to the ``Pizza``) -``pk_set`` ``[t.id]`` (since only ``Topping t`` was added to the relation) +``pk_set`` ``set([t.id])`` (since only ``Topping t`` was added to the relation) ``using`` ``"default"`` (since the default router sends writes here) ============== ============================================================ @@ -334,7 +334,7 @@ Argument Value ``model`` ``Pizza`` (the class of the objects removed from the ``Topping``) -``pk_set`` ``[p.id]`` (since only ``Pizza p`` was removed from the +``pk_set`` ``set([p.id])`` (since only ``Pizza p`` was removed from the relation) ``using`` ``"default"`` (since the default router sends writes here) -- cgit v1.3 From e10757ff4dbbc1aedd09df6c542948409c49d75f Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Tue, 25 Jun 2013 07:50:43 -0400 Subject: Doc cleanup for FormMixin.prefix; refs #18872. --- docs/ref/class-based-views/flattened-index.txt | 3 +++ docs/ref/class-based-views/mixins-editing.txt | 9 ++++++++- docs/releases/1.6.txt | 10 +++++++--- 3 files changed, 18 insertions(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/ref/class-based-views/flattened-index.txt b/docs/ref/class-based-views/flattened-index.txt index 7634a07300..272c852181 100644 --- a/docs/ref/class-based-views/flattened-index.txt +++ b/docs/ref/class-based-views/flattened-index.txt @@ -151,6 +151,7 @@ FormView * :attr:`~django.views.generic.edit.FormMixin.form_class` [:meth:`~django.views.generic.edit.FormMixin.get_form_class`] * :attr:`~django.views.generic.base.View.http_method_names` * :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`] +* :attr:`~django.views.generic.edit.FormMixin.prefix` [:meth:`~django.views.generic.edit.FormMixin.get_prefix`] * :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`] * :attr:`~django.views.generic.edit.FormMixin.success_url` [:meth:`~django.views.generic.edit.FormMixin.get_success_url`] * :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`] @@ -183,6 +184,7 @@ CreateView * :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`] * :attr:`~django.views.generic.detail.SingleObjectMixin.model` * :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg` +* :attr:`~django.views.generic.edit.FormMixin.prefix` [:meth:`~django.views.generic.edit.FormMixin.get_prefix`] * :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`] * :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`] * :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`] @@ -223,6 +225,7 @@ UpdateView * :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`] * :attr:`~django.views.generic.detail.SingleObjectMixin.model` * :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg` +* :attr:`~django.views.generic.edit.FormMixin.prefix` [:meth:`~django.views.generic.edit.FormMixin.get_prefix`] * :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`] * :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`] * :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`] diff --git a/docs/ref/class-based-views/mixins-editing.txt b/docs/ref/class-based-views/mixins-editing.txt index 23b781c2e4..bf1c10df13 100644 --- a/docs/ref/class-based-views/mixins-editing.txt +++ b/docs/ref/class-based-views/mixins-editing.txt @@ -39,7 +39,7 @@ FormMixin .. versionadded:: 1.6 - Sets the :attr:`~django.forms.Form.prefix` for the generated form. + The :attr:`~django.forms.Form.prefix` for the generated form. .. method:: get_initial() @@ -64,6 +64,13 @@ FormMixin request is a ``POST`` or ``PUT``, the request data (``request.POST`` and ``request.FILES``) will also be provided. + .. method:: get_prefix() + + .. versionadded:: 1.6 + + Determine the :attr:`~django.forms.Form.prefix` for the generated form. + Returns :attr:`~django.views.generic.edit.FormMixin.prefix` by default. + .. method:: get_success_url() Determine the URL to redirect to when the form is successfully diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 086c10c389..5d1a37ac53 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -330,6 +330,13 @@ Minor features behavior of clearing filters by setting the :attr:`~django.contrib.admin.ModelAdmin.preserve_filters` attribute to ``False``. +* Added + :meth:`FormMixin.get_prefix` + (which returns + :attr:`FormMixin.prefix` by + default) to allow customizing the :attr:`~django.forms.Form.prefix` of the + form. + Backwards incompatible changes in 1.6 ===================================== @@ -731,9 +738,6 @@ Miscellaneous of the admin views. You should update your custom templates if they use the previous parameter name. -* Added :attr:`~django.views.generic.edit.FormMixin.prefix` to allow you to - customize the prefix on the form. - Features deprecated in 1.6 ========================== -- cgit v1.3 From b91787910c9d5a036674d46a73d1b48ca33123a3 Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Sat, 22 Jun 2013 21:48:09 -0400 Subject: Fixed #20642 -- Deprecated `Option.get_(add|change|delete)_permission`. Those methods were only used by `contrib.admin` internally and exclusively related to `contrib.auth`. Since they were undocumented but used in the wild the raised deprecation warning point to an also undocumented alternative that lives in `contrib.auth`. Also did some PEP8 and other cleanups in the affected modules. --- django/contrib/admin/options.py | 100 ++++++++++++++++------------- django/contrib/auth/__init__.py | 15 ++++- django/contrib/auth/management/__init__.py | 12 ++-- django/db/models/options.py | 24 +++++++ docs/releases/1.6.txt | 7 ++ 5 files changed, 106 insertions(+), 52 deletions(-) (limited to 'docs') diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index ce10cf72ba..fd516cb512 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -4,18 +4,15 @@ from functools import partial, reduce, update_wrapper from django import forms from django.conf import settings -from django.forms.formsets import all_valid, DELETION_FIELD_NAME -from django.forms.models import (modelform_factory, modelformset_factory, - inlineformset_factory, BaseInlineFormSet, modelform_defines_fields) -from django.contrib.contenttypes.models import ContentType +from django.contrib import messages from django.contrib.admin import widgets, helpers from django.contrib.admin.util import (unquote, flatten_fieldsets, get_deleted_objects, model_format_dict, NestedObjects, lookup_needs_distinct) from django.contrib.admin import validation from django.contrib.admin.templatetags.admin_static import static from django.contrib.admin.templatetags.admin_urls import add_preserved_filters -from django.contrib import messages -from django.views.decorators.csrf import csrf_protect +from django.contrib.auth import get_permission_codename +from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied, ValidationError, FieldError from django.core.paginator import Paginator from django.core.urlresolvers import reverse @@ -24,6 +21,9 @@ from django.db.models.constants import LOOKUP_SEP from django.db.models.related import RelatedObject from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist from django.db.models.sql.constants import QUERY_TERMS +from django.forms.formsets import all_valid, DELETION_FIELD_NAME +from django.forms.models import (modelform_factory, modelformset_factory, + inlineformset_factory, BaseInlineFormSet, modelform_defines_fields) from django.http import Http404, HttpResponseRedirect from django.http.response import HttpResponseBase from django.shortcuts import get_object_or_404 @@ -39,6 +39,8 @@ from django.utils.text import capfirst, get_text_list from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils.encoding import force_text +from django.views.decorators.csrf import csrf_protect + IS_POPUP_VAR = '_popup' @@ -58,15 +60,15 @@ FORMFIELD_FOR_DBFIELD_DEFAULTS = { 'form_class': forms.SplitDateTimeField, 'widget': widgets.AdminSplitDateTime }, - models.DateField: {'widget': widgets.AdminDateWidget}, - models.TimeField: {'widget': widgets.AdminTimeWidget}, - models.TextField: {'widget': widgets.AdminTextareaWidget}, - models.URLField: {'widget': widgets.AdminURLFieldWidget}, - models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget}, + models.DateField: {'widget': widgets.AdminDateWidget}, + models.TimeField: {'widget': widgets.AdminTimeWidget}, + models.TextField: {'widget': widgets.AdminTextareaWidget}, + models.URLField: {'widget': widgets.AdminURLFieldWidget}, + models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget}, - models.CharField: {'widget': widgets.AdminTextInputWidget}, - models.ImageField: {'widget': widgets.AdminFileWidget}, - models.FileField: {'widget': widgets.AdminFileWidget}, + models.CharField: {'widget': widgets.AdminTextInputWidget}, + models.ImageField: {'widget': widgets.AdminFileWidget}, + models.FileField: {'widget': widgets.AdminFileWidget}, } csrf_protect_m = method_decorator(csrf_protect) @@ -352,7 +354,8 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)): Can be overridden by the user in subclasses. """ opts = self.opts - return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) + codename = get_permission_codename('add', opts) + return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_change_permission(self, request, obj=None): """ @@ -366,7 +369,8 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)): request has permission to change *any* object of the given type. """ opts = self.opts - return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission()) + codename = get_permission_codename('change', opts) + return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): """ @@ -380,7 +384,9 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)): request has permission to delete *any* object of the given type. """ opts = self.opts - return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission()) + codename = get_permission_codename('delete', opts) + return request.user.has_perm("%s.%s" % (opts.app_label, codename)) + class ModelAdmin(BaseModelAdmin): "Encapsulates all admin options and functionality for a given model." @@ -608,11 +614,11 @@ class ModelAdmin(BaseModelAdmin): """ from django.contrib.admin.models import LogEntry, ADDITION LogEntry.objects.log_action( - user_id = request.user.pk, - content_type_id = ContentType.objects.get_for_model(object).pk, - object_id = object.pk, - object_repr = force_text(object), - action_flag = ADDITION + user_id=request.user.pk, + content_type_id=ContentType.objects.get_for_model(object).pk, + object_id=object.pk, + object_repr=force_text(object), + action_flag=ADDITION ) def log_change(self, request, object, message): @@ -623,12 +629,12 @@ class ModelAdmin(BaseModelAdmin): """ from django.contrib.admin.models import LogEntry, CHANGE LogEntry.objects.log_action( - user_id = request.user.pk, - content_type_id = ContentType.objects.get_for_model(object).pk, - object_id = object.pk, - object_repr = force_text(object), - action_flag = CHANGE, - change_message = message + user_id=request.user.pk, + content_type_id=ContentType.objects.get_for_model(object).pk, + object_id=object.pk, + object_repr=force_text(object), + action_flag=CHANGE, + change_message=message ) def log_deletion(self, request, object, object_repr): @@ -640,11 +646,11 @@ class ModelAdmin(BaseModelAdmin): """ from django.contrib.admin.models import LogEntry, DELETION LogEntry.objects.log_action( - user_id = request.user.pk, - content_type_id = ContentType.objects.get_for_model(self.model).pk, - object_id = object.pk, - object_repr = object_repr, - action_flag = DELETION + user_id=request.user.pk, + content_type_id=ContentType.objects.get_for_model(self.model).pk, + object_id=object.pk, + object_repr=object_repr, + action_flag=DELETION ) def action_checkbox(self, obj): @@ -880,7 +886,7 @@ class ModelAdmin(BaseModelAdmin): 'has_add_permission': self.has_add_permission(request), 'has_change_permission': self.has_change_permission(request, obj), 'has_delete_permission': self.has_delete_permission(request, obj), - 'has_file_field': True, # FIXME - this should check if form or formsets have a FileField, + 'has_file_field': True, # FIXME - this should check if form or formsets have a FileField, 'has_absolute_url': hasattr(self.model, 'get_absolute_url'), 'form_url': form_url, 'opts': opts, @@ -1050,7 +1056,7 @@ class ModelAdmin(BaseModelAdmin): if action_form.is_valid(): action = action_form.cleaned_data['action'] select_across = action_form.cleaned_data['select_across'] - func, name, description = self.get_actions(request)[action] + func = self.get_actions(request)[action][0] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform @@ -1281,7 +1287,7 @@ class ModelAdmin(BaseModelAdmin): actions = self.get_actions(request) if actions: # Add the action checkboxes if there are any actions available. - list_display = ['action_checkbox'] + list(list_display) + list_display = ['action_checkbox'] + list(list_display) ChangeList = self.get_changelist(request) try: @@ -1430,7 +1436,10 @@ class ModelAdmin(BaseModelAdmin): raise PermissionDenied if obj is None: - raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)}) + raise Http404( + _('%(name)s object with primary key %(key)r does not exist.') % + {'name': force_text(opts.verbose_name), 'key': escape(object_id)} + ) using = router.db_for_write(self.model) @@ -1439,7 +1448,7 @@ class ModelAdmin(BaseModelAdmin): (deleted_objects, perms_needed, protected) = get_deleted_objects( [obj], opts, request.user, self.admin_site, using) - if request.POST: # The user has already confirmed the deletion. + if request.POST: # The user has already confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = force_text(obj) @@ -1457,7 +1466,9 @@ class ModelAdmin(BaseModelAdmin): (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) - post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url) + post_url = add_preserved_filters( + {'preserved_filters': preserved_filters, 'opts': opts}, post_url + ) else: post_url = reverse('admin:index', current_app=self.admin_site.name) @@ -1523,6 +1534,7 @@ class ModelAdmin(BaseModelAdmin): "admin/object_history.html" ], context, current_app=self.admin_site.name) + class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. @@ -1666,8 +1678,7 @@ class InlineModelAdmin(BaseModelAdmin): # to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request) - return request.user.has_perm( - self.opts.app_label + '.' + self.opts.get_add_permission()) + return super(InlineModelAdmin, self).has_add_permission(request) def has_change_permission(self, request, obj=None): opts = self.opts @@ -1678,8 +1689,8 @@ class InlineModelAdmin(BaseModelAdmin): if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break - return request.user.has_perm( - opts.app_label + '.' + opts.get_change_permission()) + codename = get_permission_codename('change', opts) + return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): if self.opts.auto_created: @@ -1688,8 +1699,7 @@ class InlineModelAdmin(BaseModelAdmin): # to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request, obj) - return request.user.has_perm( - self.opts.app_label + '.' + self.opts.get_delete_permission()) + return super(InlineModelAdmin, self).has_delete_permission(request, obj) class StackedInline(InlineModelAdmin): diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py index 029193d582..2f620a34fe 100644 --- a/django/contrib/auth/__init__.py +++ b/django/contrib/auth/__init__.py @@ -108,7 +108,9 @@ def logout(request): def get_user_model(): - "Return the User model that is active in this project" + """ + Returns the User model that is active in this project. + """ from django.db.models import get_model try: @@ -122,6 +124,10 @@ def get_user_model(): def get_user(request): + """ + Returns the user model instance associated with the given request session. + If no user is retrieved an instance of `AnonymousUser` is returned. + """ from .models import AnonymousUser try: user_id = request.session[SESSION_KEY] @@ -132,3 +138,10 @@ def get_user(request): except (KeyError, AssertionError): user = AnonymousUser() return user + + +def get_permission_codename(action, opts): + """ + Returns the codename of the permission for the specified action. + """ + return '%s_%s' % (action, opts.model_name) diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 5c1bfbc515..1f338469f8 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -6,7 +6,8 @@ from __future__ import unicode_literals import getpass import unicodedata -from django.contrib.auth import models as auth_app, get_user_model +from django.contrib.auth import (models as auth_app, get_permission_codename, + get_user_model) from django.core import exceptions from django.core.management.base import CommandError from django.db import DEFAULT_DB_ALIAS, router @@ -16,10 +17,6 @@ from django.utils import six from django.utils.six.moves import input -def _get_permission_codename(action, opts): - return '%s_%s' % (action, opts.model_name) - - def _get_all_permissions(opts, ctype): """ Returns (codename, name) for all permissions in the given opts. @@ -29,16 +26,18 @@ def _get_all_permissions(opts, ctype): _check_permission_clashing(custom, builtin, ctype) return builtin + custom + def _get_builtin_permissions(opts): """ Returns (codename, name) for all autogenerated permissions. """ perms = [] for action in ('add', 'change', 'delete'): - perms.append((_get_permission_codename(action, opts), + perms.append((get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw))) return perms + def _check_permission_clashing(custom, builtin, ctype): """ Check that permissions for a model do not clash. Raises CommandError if @@ -58,6 +57,7 @@ def _check_permission_clashing(custom, builtin, ctype): (codename, ctype.app_label, ctype.model_class().__name__)) pool.add(codename) + def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs): try: get_model('auth', 'Permission') diff --git a/django/db/models/options.py b/django/db/models/options.py index b8a79023e8..ad25de4a3e 100644 --- a/django/db/models/options.py +++ b/django/db/models/options.py @@ -414,12 +414,36 @@ class Options(object): return cache def get_add_permission(self): + """ + This method has been deprecated in favor of + `django.contrib.auth.get_permission_codename`. refs #20642 + """ + warnings.warn( + "`Options.get_add_permission` has been deprecated in favor " + "of `django.contrib.auth.get_permission_codename`.", + PendingDeprecationWarning, stacklevel=2) return 'add_%s' % self.model_name def get_change_permission(self): + """ + This method has been deprecated in favor of + `django.contrib.auth.get_permission_codename`. refs #20642 + """ + warnings.warn( + "`Options.get_change_permission` has been deprecated in favor " + "of `django.contrib.auth.get_permission_codename`.", + PendingDeprecationWarning, stacklevel=2) return 'change_%s' % self.model_name def get_delete_permission(self): + """ + This method has been deprecated in favor of + `django.contrib.auth.get_permission_codename`. refs #20642 + """ + warnings.warn( + "`Options.get_delete_permission` has been deprecated in favor " + "of `django.contrib.auth.get_permission_codename`.", + PendingDeprecationWarning, stacklevel=2) return 'delete_%s' % self.model_name def get_all_related_objects(self, local_only=False, include_hidden=False, diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 5d1a37ac53..3d59ce771b 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -855,6 +855,13 @@ on a widget, you should now define this method on the form field itself. ``Model._meta.module_name`` was renamed to ``model_name``. Despite being a private API, it will go through a regular deprecation path. +``get_(add|change|delete)_permission`` model _meta methods +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Model._meta.get_(add|change|delete)_permission`` methods were deprecated. +Even if they were not part of the public API they'll also go through +a regular deprecation path. + ``get_query_set`` and similar methods renamed to ``get_queryset`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- cgit v1.3 From c6862d57c1e987f0f98a77826d19358b9040bad1 Mon Sep 17 00:00:00 2001 From: Loic Bistuer Date: Wed, 26 Jun 2013 18:25:24 +0700 Subject: Fixed #20658 -- Fixed bad reST formatting and missing parentheses in the docs for CBV mixins Thanks to Keryn Knight for the report. --- docs/topics/class-based-views/mixins.txt | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) (limited to 'docs') diff --git a/docs/topics/class-based-views/mixins.txt b/docs/topics/class-based-views/mixins.txt index b6552b9108..84d7417233 100644 --- a/docs/topics/class-based-views/mixins.txt +++ b/docs/topics/class-based-views/mixins.txt @@ -34,7 +34,7 @@ interface to working with templates in class-based views. :class:`~django.views.generic.base.TemplateResponseMixin` Every built in view which returns a :class:`~django.template.response.TemplateResponse` will call the - :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response` + :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()` method that ``TemplateResponseMixin`` provides. Most of the time this will be called for you (for instance, it is called by the ``get()`` method implemented by both :class:`~django.views.generic.base.TemplateView` and @@ -44,7 +44,7 @@ interface to working with templates in class-based views. it. For an example of this, see the :ref:`JSONResponseMixin example `. - ``render_to_response`` itself calls + ``render_to_response()`` itself calls :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`, which by default will just look up :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` on @@ -60,9 +60,9 @@ interface to working with templates in class-based views. :class:`~django.views.generic.base.ContextMixin` Every built in view which needs context data, such as for rendering a template (including ``TemplateResponseMixin`` above), should call - :meth:`~django.views.generic.base.ContextMixin.get_context_data` passing + :meth:`~django.views.generic.base.ContextMixin.get_context_data()` passing any data they want to ensure is in there as keyword arguments. - ``get_context_data`` returns a dictionary; in ``ContextMixin`` it + ``get_context_data()`` returns a dictionary; in ``ContextMixin`` it simply returns its keyword arguments, but it is common to override this to add more members to the dictionary. @@ -107,7 +107,7 @@ URLConf, and looks the object up either from the on the view, or the :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` attribute if that's provided). ``SingleObjectMixin`` also overrides -:meth:`~django.views.generic.base.ContextMixin.get_context_data`, +:meth:`~django.views.generic.base.ContextMixin.get_context_data()`, which is used across all Django's built in class-based views to supply context data for template renders. @@ -152,7 +152,7 @@ here would be to dynamically vary the objects, such as depending on the current user or to exclude posts in the future for a blog. :class:`~django.views.generic.list.MultipleObjectMixin` also overrides -:meth:`~django.views.generic.base.ContextMixin.get_context_data` to +:meth:`~django.views.generic.base.ContextMixin.get_context_data()` to include appropriate context variables for pagination (providing dummies if pagination is disabled). It relies on ``object_list`` being passed in as a keyword argument, which :class:`ListView` arranges for @@ -286,15 +286,16 @@ One way to do this is to combine :class:`ListView` with for the paginated list of books can hang off the publisher found as the single object. In order to do this, we need to have two different querysets: -**``Publisher`` queryset for use in ``get_object``** +``Publisher`` queryset for use in + :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()` We'll set the ``model`` attribute on the view and rely on the default implementation of ``get_object()`` to fetch the correct ``Publisher`` object. -**``Book`` queryset for use by ``ListView``** - The default implementation of ``get_queryset`` uses the ``model`` attribute +``Book`` queryset for use by :class:`~django.views.generic.list.ListView` + The default implementation of ``get_queryset()`` uses the ``model`` attribute to construct the queryset. This conflicts with our use of this attribute - for ``get_object`` so we'll override that method and have it return + for ``get_object()`` so we'll override that method and have it return the queryset of ``Book`` objects linked to the ``Publisher`` we're looking at. @@ -641,10 +642,10 @@ For example, a simple JSON mixin might look something like this:: information on how to correctly transform Django models and querysets into JSON. -This mixin provides a ``render_to_json_response`` method with the same signature +This mixin provides a ``render_to_json_response()`` method with the same signature as :func:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`. To use it, we simply need to mix it into a ``TemplateView`` for example, -and override ``render_to_response`` to call ``render_to_json_response`` instead:: +and override ``render_to_response()`` to call ``render_to_json_response()`` instead:: from django.views.generic import TemplateView @@ -693,5 +694,5 @@ that the user requested:: Because of the way that Python resolves method overloading, the call to ``super(HybridDetailView, self).render_to_response(context)`` ends up calling the -:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response` +:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()` implementation of :class:`~django.views.generic.base.TemplateResponseMixin`. -- cgit v1.3 From 1184d077893ff1bc947e45b00a4d565f3df81776 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Fri, 21 Jun 2013 16:59:33 -0400 Subject: Fixed #14881 -- Modified password reset to work with a non-integer UserModel.pk. uid is now base64 encoded in password reset URLs/views. A backwards compatible password_reset_confirm view/URL will allow password reset links generated before this change to continue to work. This view will be removed in Django 1.7. Thanks jonash for the initial patch and claudep for the review. --- .../registration/password_reset_email.html | 2 +- django/contrib/auth/forms.py | 5 +- .../registration/password_reset_email.html | 2 +- django/contrib/auth/tests/test_views.py | 24 +++++++++- django/contrib/auth/tests/urls.py | 5 +- django/contrib/auth/urls.py | 3 ++ django/contrib/auth/views.py | 21 ++++++--- django/utils/http.py | 21 ++++++++- docs/internals/deprecation.txt | 8 ++++ docs/ref/contrib/admin/index.txt | 7 ++- docs/ref/utils.txt | 14 ++++++ docs/releases/1.6.txt | 53 ++++++++++++++++++++++ docs/topics/auth/default.txt | 22 ++++++--- 13 files changed, 164 insertions(+), 23 deletions(-) (limited to 'docs') diff --git a/django/contrib/admin/templates/registration/password_reset_email.html b/django/contrib/admin/templates/registration/password_reset_email.html index 44ae5850b1..01b3bccbbc 100644 --- a/django/contrib/admin/templates/registration/password_reset_email.html +++ b/django/contrib/admin/templates/registration/password_reset_email.html @@ -3,7 +3,7 @@ {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} -{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb36=uid token=token %} +{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index a9ecba45c2..43f5303b63 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -6,8 +6,9 @@ from django import forms from django.forms.util import flatatt from django.template import loader from django.utils.datastructures import SortedDict +from django.utils.encoding import force_bytes from django.utils.html import format_html, format_html_join -from django.utils.http import int_to_base36 +from django.utils.http import urlsafe_base64_encode from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import ugettext, ugettext_lazy as _ @@ -243,7 +244,7 @@ class PasswordResetForm(forms.Form): 'email': user.email, 'domain': domain, 'site_name': site_name, - 'uid': int_to_base36(user.pk), + 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', diff --git a/django/contrib/auth/tests/templates/registration/password_reset_email.html b/django/contrib/auth/tests/templates/registration/password_reset_email.html index 1b9a48255a..baac2fc2dd 100644 --- a/django/contrib/auth/tests/templates/registration/password_reset_email.html +++ b/django/contrib/auth/tests/templates/registration/password_reset_email.html @@ -1 +1 @@ -{{ protocol }}://{{ domain }}/reset/{{ uid }}-{{ token }}/ \ No newline at end of file +{{ protocol }}://{{ domain }}/reset/{{ uid }}/{{ token }}/ diff --git a/django/contrib/auth/tests/test_views.py b/django/contrib/auth/tests/test_views.py index 3a1be5bb7b..ba06a6af4d 100644 --- a/django/contrib/auth/tests/test_views.py +++ b/django/contrib/auth/tests/test_views.py @@ -13,7 +13,7 @@ from django.core import mail from django.core.urlresolvers import reverse, NoReverseMatch from django.http import QueryDict, HttpRequest from django.utils.encoding import force_text -from django.utils.http import urlquote +from django.utils.http import int_to_base36, urlsafe_base64_decode, urlquote from django.utils._os import upath from django.test import TestCase from django.test.utils import override_settings, patch_logger @@ -91,7 +91,7 @@ class AuthViewNamedURLTests(AuthViewsTestCase): ('password_reset', [], {}), ('password_reset_done', [], {}), ('password_reset_confirm', [], { - 'uidb36': 'aaaaaaa', + 'uidb64': 'aaaaaaa', 'token': '1111-aaaaa', }), ('password_reset_complete', [], {}), @@ -193,6 +193,16 @@ class PasswordResetTest(AuthViewsTestCase): # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") + def test_confirm_valid_base36(self): + # Remove in Django 1.7 + url, path = self._test_confirm_start() + path_parts = path.strip("/").split("/") + # construct an old style (base36) URL by converting the base64 ID + path_parts[1] = int_to_base36(int(urlsafe_base64_decode(path_parts[1]))) + response = self.client.get("/%s/%s-%s/" % tuple(path_parts)) + # redirect to a 'complete' page: + self.assertContains(response, "Please enter your new password") + def test_confirm_invalid(self): url, path = self._test_confirm_start() # Let's munge the token in the path, but keep the same length, @@ -204,11 +214,21 @@ class PasswordResetTest(AuthViewsTestCase): def test_confirm_invalid_user(self): # Ensure that we get a 200 response for a non-existant user, not a 404 + response = self.client.get('/reset/123456/1-1/') + self.assertContains(response, "The password reset link was invalid") + + def test_confirm_invalid_user_base36(self): + # Remove in Django 1.7 response = self.client.get('/reset/123456-1-1/') self.assertContains(response, "The password reset link was invalid") def test_confirm_overflow_user(self): # Ensure that we get a 200 response for a base36 user id that overflows int + response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/') + self.assertContains(response, "The password reset link was invalid") + + def test_confirm_overflow_user_base36(self): + # Remove in Django 1.7 response = self.client.get('/reset/zzzzzzzzzzzzz-1-1/') self.assertContains(response, "The password reset link was invalid") diff --git a/django/contrib/auth/tests/urls.py b/django/contrib/auth/tests/urls.py index 835ff41de7..502fc659d4 100644 --- a/django/contrib/auth/tests/urls.py +++ b/django/contrib/auth/tests/urls.py @@ -67,10 +67,10 @@ urlpatterns = urlpatterns + patterns('', (r'^password_reset_from_email/$', 'django.contrib.auth.views.password_reset', dict(from_email='staffmember@example.com')), (r'^password_reset/custom_redirect/$', 'django.contrib.auth.views.password_reset', dict(post_reset_redirect='/custom/')), (r'^password_reset/custom_redirect/named/$', 'django.contrib.auth.views.password_reset', dict(post_reset_redirect='password_reset')), - (r'^reset/custom/(?P[0-9A-Za-z]{1,13})-(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', + (r'^reset/custom/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', dict(post_reset_redirect='/custom/')), - (r'^reset/custom/named/(?P[0-9A-Za-z]{1,13})-(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', + (r'^reset/custom/named/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', dict(post_reset_redirect='password_reset')), (r'^password_change/custom/$', 'django.contrib.auth.views.password_change', dict(post_change_redirect='/custom/')), @@ -88,4 +88,3 @@ urlpatterns = urlpatterns + patterns('', (r'^custom_request_auth_login/$', custom_request_auth_login), url(r'^userpage/(.+)/$', userpage, name="userpage"), ) - diff --git a/django/contrib/auth/urls.py b/django/contrib/auth/urls.py index c5e87ed2eb..801d133437 100644 --- a/django/contrib/auth/urls.py +++ b/django/contrib/auth/urls.py @@ -12,7 +12,10 @@ urlpatterns = patterns('', url(r'^password_change/done/$', 'django.contrib.auth.views.password_change_done', name='password_change_done'), url(r'^password_reset/$', 'django.contrib.auth.views.password_reset', name='password_reset'), url(r'^password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'), + # Support old style base36 password reset links; remove in Django 1.7 url(r'^reset/(?P[0-9A-Za-z]{1,13})-(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', + 'django.contrib.auth.views.password_reset_confirm_uidb36'), + url(r'^reset/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'), url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete', name='password_reset_complete'), diff --git a/django/contrib/auth/views.py b/django/contrib/auth/views.py index fe21683323..e9affb33cd 100644 --- a/django/contrib/auth/views.py +++ b/django/contrib/auth/views.py @@ -7,9 +7,10 @@ from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, QueryDict from django.template.response import TemplateResponse -from django.utils.http import base36_to_int, is_safe_url +from django.utils.http import base36_to_int, is_safe_url, urlsafe_base64_decode, urlsafe_base64_encode from django.utils.translation import ugettext as _ from django.shortcuts import resolve_url +from django.utils.encoding import force_bytes, force_text from django.views.decorators.debug import sensitive_post_parameters from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect @@ -184,7 +185,7 @@ def password_reset_done(request, # Doesn't need csrf_protect since no-one can guess the URL @sensitive_post_parameters() @never_cache -def password_reset_confirm(request, uidb36=None, token=None, +def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, @@ -195,15 +196,15 @@ def password_reset_confirm(request, uidb36=None, token=None, form for entering a new password. """ UserModel = get_user_model() - assert uidb36 is not None and token is not None # checked by URLconf + assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: - uid_int = base36_to_int(uidb36) - user = UserModel._default_manager.get(pk=uid_int) - except (ValueError, OverflowError, UserModel.DoesNotExist): + uid = urlsafe_base64_decode(uidb64) + user = UserModel._default_manager.get(pk=uid) + except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): @@ -227,6 +228,14 @@ def password_reset_confirm(request, uidb36=None, token=None, return TemplateResponse(request, template_name, context, current_app=current_app) +def password_reset_confirm_uidb36(request, uidb36=None, **kwargs): + # Support old password reset URLs that used base36 encoded user IDs. + # Remove in Django 1.7 + try: + uidb64 = force_text(urlsafe_base64_encode(force_bytes(base36_to_int(uidb36)))) + except ValueError: + uidb64 = '1' # dummy invalid ID (incorrect padding for base64) + return password_reset_confirm(request, uidb64=uidb64, **kwargs) def password_reset_complete(request, template_name='registration/password_reset_complete.html', diff --git a/django/utils/http.py b/django/utils/http.py index f4911b4ec0..4647d89847 100644 --- a/django/utils/http.py +++ b/django/utils/http.py @@ -1,5 +1,6 @@ from __future__ import unicode_literals +import base64 import calendar import datetime import re @@ -11,7 +12,7 @@ except ImportError: # Python 2 import urlparse urllib_parse.urlparse = urlparse.urlparse - +from binascii import Error as BinasciiError from email.utils import formatdate from django.utils.datastructures import MultiValueDict @@ -202,6 +203,24 @@ def int_to_base36(i): factor -= 1 return ''.join(base36) +def urlsafe_base64_encode(s): + """ + Encodes a bytestring in base64 for use in URLs, stripping any trailing + equal signs. + """ + return base64.urlsafe_b64encode(s).rstrip(b'\n=') + +def urlsafe_base64_decode(s): + """ + Decodes a base64 encoded string, adding back any trailing equal signs that + might have been stripped. + """ + s = s.encode('utf-8') # base64encode should only return ASCII. + try: + return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'=')) + except (LookupError, BinasciiError) as e: + raise ValueError(e) + def parse_etags(etag_str): """ Parses a string with one or several etags passed in If-None-Match and diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 45f82b49e6..9672746717 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -326,6 +326,14 @@ these changes. remove calls to this method, and instead ensure that their auth related views are CSRF protected, which ensures that cookies are enabled. +* The version of :func:`django.contrib.auth.views.password_reset_confirm` that + supports base36 encoded user IDs + (``django.contrib.auth.views.password_reset_confirm_uidb36``) will be + removed. If your site has been running Django 1.6 for more than + :setting:`PASSWORD_RESET_TIMEOUT_DAYS`, this change will have no effect. If + not, then any password reset links generated before you upgrade to Django 1.7 + won't work after the upgrade. + 1.8 --- diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index 90ef68837a..318ce297a2 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -2278,9 +2278,14 @@ your URLconf. Specifically, add these four patterns: url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='admin_password_reset'), url(r'^admin/password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'), - url(r'^reset/(?P[0-9A-Za-z]+)-(?P.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'), + url(r'^reset/(?P[0-9A-Za-z_\-]+)/(?P.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'), url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete', name='password_reset_complete'), +.. versionchanged:: 1.6 + + The pattern for :func:`~django.contrib.auth.views.password_reset_confirm` + changed as the ``uid`` is now base 64 encoded. + (This assumes you've added the admin at ``admin/`` and requires that you put the URLs starting with ``^admin/`` before the line that includes the admin app itself). diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt index 45d7781403..8d722829fb 100644 --- a/docs/ref/utils.txt +++ b/docs/ref/utils.txt @@ -649,6 +649,20 @@ escaping HTML. Converts a positive integer to a base 36 string. On Python 2 ``i`` must be smaller than :data:`sys.maxint`. +.. function:: urlsafe_base64_encode(s) + + .. versionadded:: 1.6 + + Encodes a bytestring in base64 for use in URLs, stripping any trailing + equal signs. + +.. function:: urlsafe_base64_decode(s) + + .. versionadded:: 1.6 + + Decodes a base64 encoded string, adding back any trailing equal signs that + might have been stripped. + ``django.utils.module_loading`` =============================== diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 3d59ce771b..2c1fffd8cd 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -656,6 +656,59 @@ rely on the previous URLs. If you want to revert to the original behavior you can set the :attr:`~django.contrib.admin.ModelAdmin.preserve_filters` attribute to ``False``. +``django.contrib.auth`` password reset uses base 64 encoding of ``User`` PK +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Past versions of Django used base 36 encoding of the ``User`` primary key in +the password reset views and URLs +(:func:`django.contrib.auth.views.password_reset_confirm`). Base 36 encoding is +sufficient if the user primary key is an integer, however, with the +introduction of custom user models in Django 1.5, that assumption may no longer +be true. + +:func:`django.contrib.auth.views.password_reset_confirm` has been modified to +take a ``uidb64`` parameter instead of ``uidb36``. If you are reversing this +view, for example in a custom ``password_reset_email.html`` template, be sure +to update your code. + +A temporary shim for :func:`django.contrib.auth.views.password_reset_confirm` +that will allow password reset links generated prior to Django 1.6 to continue +to work has been added to provide backwards compatibility; this will be removed +in Django 1.7. Thus, as long as your site has been running Django 1.6 for more +than :setting:`PASSWORD_RESET_TIMEOUT_DAYS`, this change will have no effect. +If not (for example, if you upgrade directly from Django 1.5 to Django 1.7), +then any password reset links generated before you upgrade to Django 1.7 or +later won't work after the upgrade. + +In addition, if you have any custom password reset URLs, you will need to +update them by replacing ``uidb36`` with ``uidb64`` and the dash that follows +that pattern with a slash. Also add ``_\-`` to the list of characters that may +match the ``uidb64`` pattern. + +For example:: + + url(r'^reset/(?P[0-9A-Za-z]+)-(?P.+)/$', + 'django.contrib.auth.views.password_reset_confirm', + name='password_reset_confirm'), + +becomes:: + + url(r'^reset/(?P[0-9A-Za-z_\-]+)/(?P.+)/$', + 'django.contrib.auth.views.password_reset_confirm', + name='password_reset_confirm'), + +You may also want to add the shim to support the old style reset links. Using +the example above, you would modify the existing url by replacing +``django.contrib.auth.views.password_reset_confirm`` with +``django.contrib.auth.views.password_reset_confirm_uidb36`` and also remove +the ``name`` argument so it doesn't conflict with the new url:: + + url(r'^reset/(?P[0-9A-Za-z]+)-(?P.+)/$', + 'django.contrib.auth.views.password_reset_confirm_uidb36'), + +You can remove this url pattern after your app has been deployed with Django +1.6 for :setting:`PASSWORD_RESET_TIMEOUT_DAYS`. + Miscellaneous ~~~~~~~~~~~~~ diff --git a/docs/topics/auth/default.txt b/docs/topics/auth/default.txt index 8849520b11..e2fa0c287e 100644 --- a/docs/topics/auth/default.txt +++ b/docs/topics/auth/default.txt @@ -817,7 +817,7 @@ patterns. * ``protocol``: http or https - * ``uid``: The user's id encoded in base 36. + * ``uid``: The user's primary key encoded in base 64. * ``token``: Token to check that the reset link is valid. @@ -826,7 +826,12 @@ patterns. .. code-block:: html+django Someone asked for password reset for email {{ email }}. Follow the link below: - {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb36=uid token=token %} + {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} + + .. versionchanged:: 1.6 + + Reversing ``password_reset_confirm`` takes a ``uidb64`` argument instead + of ``uidb36``. The same template context is used for subject template. Subject must be single line plain text string. @@ -846,7 +851,7 @@ patterns. Defaults to :file:`registration/password_reset_done.html` if not supplied. -.. function:: password_reset_confirm(request[, uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect]) +.. function:: password_reset_confirm(request[, uidb64, token, template_name, token_generator, set_password_form, post_reset_redirect]) Presents a form for entering a new password. @@ -854,7 +859,12 @@ patterns. **Optional arguments:** - * ``uidb36``: The user's id encoded in base 36. Defaults to ``None``. + * ``uidb64``: The user's id encoded in base 64. Defaults to ``None``. + + .. versionchanged:: 1.6 + + The ``uidb64`` parameter was previously base 36 encoded and named + ``uidb36``. * ``token``: Token to check that the password is valid. Defaults to ``None``. @@ -877,8 +887,8 @@ patterns. * ``form``: The form (see ``set_password_form`` above) for setting the new user's password. - * ``validlink``: Boolean, True if the link (combination of uidb36 and - token) is valid or unused yet. + * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and + ``token``) is valid or unused yet. .. function:: password_reset_complete(request[,template_name]) -- cgit v1.3 From 2ec54e7fbcec658844e3fd0515d9990291d954a6 Mon Sep 17 00:00:00 2001 From: Trey Hunner Date: Wed, 26 Jun 2013 10:25:34 -0700 Subject: Add missing preposition in documentation --- docs/howto/custom-model-fields.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt index 8993872cff..54913a887a 100644 --- a/docs/howto/custom-model-fields.txt +++ b/docs/howto/custom-model-fields.txt @@ -31,7 +31,7 @@ Our example object Creating custom fields requires a bit of attention to detail. To make things easier to follow, we'll use a consistent example throughout this document: wrapping a Python object representing the deal of cards in a hand of Bridge_. -Don't worry, you don't have know how to play Bridge to follow this example. +Don't worry, you don't have to know how to play Bridge to follow this example. You only need to know that 52 cards are dealt out equally to four players, who are traditionally called *north*, *east*, *south* and *west*. Our class looks something like this:: -- cgit v1.3 From 5005303ae7919eef26dab9f8ba279696966ebf1d Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Thu, 27 Jun 2013 09:42:09 +0200 Subject: Fixed #20665 -- Missing backslash in sitemaps documentation Thanks to roman for the report. --- docs/ref/contrib/sitemaps.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt index 56a15cb9e0..4467ed3a6e 100644 --- a/docs/ref/contrib/sitemaps.txt +++ b/docs/ref/contrib/sitemaps.txt @@ -358,7 +358,7 @@ with a caching decorator -- you must name your sitemap view and pass from django.views.decorators.cache import cache_page urlpatterns = patterns('', - url(r'^sitemap.xml$', + url(r'^sitemap\.xml$', cache_page(86400)(sitemaps_views.index), {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}), url(r'^sitemap-(?P
.+)\.xml$', -- cgit v1.3 From e26b589b8cd2c46c0e6af360abaacdb2fb0af27d Mon Sep 17 00:00:00 2001 From: Andrew Godwin Date: Thu, 27 Jun 2013 14:02:00 +0100 Subject: Fixed #20590: Documented new test case ordering --- docs/topics/testing/overview.txt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/topics/testing/overview.txt b/docs/topics/testing/overview.txt index 8268051a36..d56b1be20f 100644 --- a/docs/topics/testing/overview.txt +++ b/docs/topics/testing/overview.txt @@ -221,10 +221,12 @@ Order in which tests are executed In order to guarantee that all ``TestCase`` code starts with a clean database, the Django test runner reorders tests in the following way: -* First, all unittests (including :class:`unittest.TestCase`, - :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and - :class:`~django.test.TransactionTestCase`) are run with no particular ordering - guaranteed nor enforced among them. +* All :class:`~django.test.TestCase` subclasses are run first. + +* Then, all other unittests (including :class:`unittest.TestCase`, + :class:`~django.test.SimpleTestCase` and + :class:`~django.test.TransactionTestCase`) are run with no particular + ordering guaranteed nor enforced among them. * Then any other tests (e.g. doctests) that may alter the database without restoring it to its original state are run. -- cgit v1.3 From 8db264cbc88e46eb8bc79e8e819a72f814db503e Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Thu, 27 Jun 2013 16:29:26 +0200 Subject: Fixed LOGGING setting docs --- docs/ref/settings.txt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index 902eefa86a..215931768c 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -1350,8 +1350,14 @@ A data structure containing configuration information. The contents of this data structure will be passed as the argument to the configuration method described in :setting:`LOGGING_CONFIG`. -The default logging configuration passes HTTP 500 server errors to an -email log handler; all other log messages are given to a NullHandler. +Among other things, the default logging configuration passes HTTP 500 server +errors to an email log handler when :setting:`DEBUG` is ``False``. See also +:ref:`configuring-logging`. + +You can see the default logging configuration by looking in +``django/utils/log.py`` (or view the `online source`__). + +__ https://github.com/django/django/blob/master/django/utils/log.py .. setting:: LOGGING_CONFIG -- cgit v1.3 From 12cb0df10f12e715bcaafbee4290c92d4ed6f111 Mon Sep 17 00:00:00 2001 From: Andrew Godwin Date: Thu, 27 Jun 2013 15:12:35 +0100 Subject: Docs for related_query_name --- docs/ref/models/fields.txt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'docs') diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 8146dfd341..f5c1058b17 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -1083,6 +1083,22 @@ define the details of how the relation works. user = models.ForeignKey(User, related_name='+') +.. attribute:: ForeignKey.related_query_name + + .. versionadded:: 1.6 + + The name to use for the reverse filter name from the target model. + Defaults to the value of :attr:`related_name` if it is set, otherwise it + defaults to the name of the model:: + + # Declare the ForeignKey with related_query_name + class Tag(models.Model): + article = models.ForeignKey(Article, related_name="tags", related_query_name="tag") + name = models.CharField(max_length=255) + + # That's now the name of the reverse filter + article_instance.filter(tag__name="important") + .. attribute:: ForeignKey.to_field The field on the related object that the relation is to. By default, Django @@ -1207,6 +1223,12 @@ that control how the relationship functions. users = models.ManyToManyField(User, related_name='u+') referents = models.ManyToManyField(User, related_name='ref+') +.. attribute:: ForeignKey.related_query_name + + .. versionadded:: 1.6 + + Same as :attr:`ForeignKey.related_query_name`. + .. attribute:: ManyToManyField.limit_choices_to Same as :attr:`ForeignKey.limit_choices_to`. -- cgit v1.3 From 6fcb7ba84239ef1f6b3451c70d40a5ae1cdffcf5 Mon Sep 17 00:00:00 2001 From: Ken Bolton Date: Thu, 27 Jun 2013 12:39:50 -0400 Subject: Fix typo --- docs/ref/signals.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/ref/signals.txt b/docs/ref/signals.txt index 0fdfb0ee14..0253832b8d 100644 --- a/docs/ref/signals.txt +++ b/docs/ref/signals.txt @@ -284,7 +284,7 @@ If we connected a handler like this:: and then did something like this:: - >>> p = Pizza.object.create(...) + >>> p = Pizza.objects.create(...) >>> t = Topping.objects.create(...) >>> p.toppings.add(t) -- cgit v1.3 From c1284c3d3c6131a9d0ded9601ae0feb9a2e81a65 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Thu, 27 Jun 2013 22:19:54 +0200 Subject: Fixed #20571 -- Added an API to control connection.needs_rollback. This is useful: - to force a rollback on the exit of an atomic block without having to raise and catch an exception; - to prevent a rollback after handling an exception manually. --- django/db/backends/__init__.py | 9 +++++++++ django/db/transaction.py | 20 ++++++++++++++++++++ docs/topics/db/transactions.txt | 21 +++++++++++++++++++++ tests/transactions/tests.py | 26 ++++++++++++++++++++++++-- 4 files changed, 74 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index fa3cc5ac02..1a74232704 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -330,6 +330,15 @@ class BaseDatabaseWrapper(object): self._set_autocommit(autocommit) self.autocommit = autocommit + def set_rollback(self, rollback): + """ + Set or unset the "needs rollback" flag -- for *advanced use* only. + """ + if not self.in_atomic_block: + raise TransactionManagementError( + "needs_rollback doesn't work outside of an 'atomic' block.") + self.needs_rollback = rollback + def validate_no_atomic_block(self): """ Raise an error if an atomic block is active. diff --git a/django/db/transaction.py b/django/db/transaction.py index f770f2efa7..95b9ae165e 100644 --- a/django/db/transaction.py +++ b/django/db/transaction.py @@ -171,6 +171,26 @@ def clean_savepoints(using=None): """ get_connection(using).clean_savepoints() +def get_rollback(using=None): + """ + Gets the "needs rollback" flag -- for *advanced use* only. + """ + return get_connection(using).needs_rollback + +def set_rollback(rollback, using=None): + """ + Sets or unsets the "needs rollback" flag -- for *advanced use* only. + + When `rollback` is `True`, it triggers a rollback when exiting the + innermost enclosing atomic block that has `savepoint=True` (that's the + default). Use this to force a rollback without raising an exception. + + When `rollback` is `False`, it prevents such a rollback. Use this only + after rolling back to a known-good state! Otherwise, you break the atomic + block and data corruption may occur. + """ + return get_connection(using).set_rollback(rollback) + ################################# # Decorators / context managers # ################################# diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index e9a626f56b..903579cc38 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -389,6 +389,27 @@ The following example demonstrates the use of savepoints:: transaction.savepoint_rollback(sid) # open transaction now contains only a.save() +.. versionadded:: 1.6 + +Savepoints may be used to recover from a database error by performing a partial +rollback. If you're doing this inside an :func:`atomic` block, the entire block +will still be rolled back, because it doesn't know you've handled the situation +at a lower level! To prevent this, you can control the rollback behavior with +the following functions. + +.. function:: get_rollback(using=None) + +.. function:: set_rollback(rollback, using=None) + +Setting the rollback flag to ``True`` forces a rollback when exiting the +innermost atomic block. This may be useful to trigger a rollback without +raising an exception. + +Setting it to ``False`` prevents such a rollback. Before doing that, make sure +you've rolled back the transaction to a known-good savepoint within the current +atomic block! Otherwise you're breaking atomicity and data corruption may +occur. + Database-specific notes ======================= diff --git a/tests/transactions/tests.py b/tests/transactions/tests.py index 24b7615d6f..756fa40abd 100644 --- a/tests/transactions/tests.py +++ b/tests/transactions/tests.py @@ -1,9 +1,8 @@ from __future__ import absolute_import import sys -import warnings -from django.db import connection, transaction, IntegrityError +from django.db import connection, transaction, DatabaseError, IntegrityError from django.test import TransactionTestCase, skipUnlessDBFeature from django.test.utils import IgnorePendingDeprecationWarningsMixin from django.utils import six @@ -188,6 +187,29 @@ class AtomicTests(TransactionTestCase): raise Exception("Oops, that's his first name") self.assertQuerysetEqual(Reporter.objects.all(), []) + def test_force_rollback(self): + with transaction.atomic(): + Reporter.objects.create(first_name="Tintin") + # atomic block shouldn't rollback, but force it. + self.assertFalse(transaction.get_rollback()) + transaction.set_rollback(True) + self.assertQuerysetEqual(Reporter.objects.all(), []) + + def test_prevent_rollback(self): + with transaction.atomic(): + Reporter.objects.create(first_name="Tintin") + sid = transaction.savepoint() + # trigger a database error inside an inner atomic without savepoint + with self.assertRaises(DatabaseError): + with transaction.atomic(savepoint=False): + connection.cursor().execute( + "SELECT no_such_col FROM transactions_reporter") + transaction.savepoint_rollback(sid) + # atomic block should rollback, but prevent it, as we just did it. + self.assertTrue(transaction.get_rollback()) + transaction.set_rollback(False) + self.assertQuerysetEqual(Reporter.objects.all(), ['']) + class AtomicInsideTransactionTests(AtomicTests): """All basic tests for atomic should also pass within an existing transaction.""" -- cgit v1.3 From d097417025e71286ad5bbde6e0a79caacabbbd64 Mon Sep 17 00:00:00 2001 From: Shai Berger Date: Fri, 28 Jun 2013 06:15:03 +0300 Subject: Support 'pyformat' style parameters in raw queries, Refs #10070 Add support for Oracle, fix an issue with the repr of RawQuerySet, add tests and documentations. Also added a 'supports_paramstyle_pyformat' database feature, True by default, False for SQLite. Thanks Donald Stufft for review of documentation. --- django/db/backends/__init__.py | 5 +++ django/db/backends/oracle/base.py | 66 ++++++++++++++++++++++++-------------- django/db/backends/sqlite3/base.py | 1 + django/db/models/query.py | 5 ++- docs/ref/databases.txt | 8 +++++ docs/releases/1.6.txt | 6 ++++ docs/topics/db/sql.txt | 25 ++++++++++++--- tests/backends/tests.py | 44 +++++++++++++++++++++++-- tests/raw_query/tests.py | 21 ++++++++++-- 9 files changed, 147 insertions(+), 34 deletions(-) (limited to 'docs') diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index 1a74232704..9abb9a9637 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -613,6 +613,11 @@ class BaseDatabaseFeatures(object): # when autocommit is disabled? http://bugs.python.org/issue8145#msg109965 autocommits_when_autocommit_is_off = False + # Does the backend support 'pyformat' style ("... %(name)s ...", {'name': value}) + # parameter passing? Note this can be provided by the backend even if not + # supported by the Python driver + supports_paramstyle_pyformat = True + def __init__(self, connection): self.connection = connection diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index 3f39a15aa7..5e2b763f52 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -757,20 +757,37 @@ class FormatStylePlaceholderCursor(object): self.cursor.arraysize = 100 def _format_params(self, params): - return tuple([OracleParam(p, self, True) for p in params]) + try: + return dict((k,OracleParam(v, self, True)) for k,v in params.items()) + except AttributeError: + return tuple([OracleParam(p, self, True) for p in params]) def _guess_input_sizes(self, params_list): - sizes = [None] * len(params_list[0]) - for params in params_list: - for i, value in enumerate(params): - if value.input_size: - sizes[i] = value.input_size - self.setinputsizes(*sizes) + # Try dict handling; if that fails, treat as sequence + if hasattr(params_list[0], 'keys'): + sizes = {} + for params in params_list: + for k, value in params.items(): + if value.input_size: + sizes[k] = value.input_size + self.setinputsizes(**sizes) + else: + # It's not a list of dicts; it's a list of sequences + sizes = [None] * len(params_list[0]) + for params in params_list: + for i, value in enumerate(params): + if value.input_size: + sizes[i] = value.input_size + self.setinputsizes(*sizes) def _param_generator(self, params): - return [p.force_bytes for p in params] + # Try dict handling; if that fails, treat as sequence + if hasattr(params, 'items'): + return dict((k, v.force_bytes) for k,v in params.items()) + else: + return [p.force_bytes for p in params] - def execute(self, query, params=None): + def _fix_for_params(self, query, params): # cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it # it does want a trailing ';' but not a trailing '/'. However, these # characters must be included in the original query in case the query @@ -780,10 +797,18 @@ class FormatStylePlaceholderCursor(object): if params is None: params = [] query = convert_unicode(query, self.charset) + elif hasattr(params, 'keys'): + # Handle params as dict + args = dict((k, ":%s"%k) for k in params.keys()) + query = convert_unicode(query % args, self.charset) else: - params = self._format_params(params) + # Handle params as sequence args = [(':arg%d' % i) for i in range(len(params))] query = convert_unicode(query % tuple(args), self.charset) + return query, self._format_params(params) + + def execute(self, query, params=None): + query, params = self._fix_for_params(query, params) self._guess_input_sizes([params]) try: return self.cursor.execute(query, self._param_generator(params)) @@ -794,22 +819,15 @@ class FormatStylePlaceholderCursor(object): raise def executemany(self, query, params=None): - # cx_Oracle doesn't support iterators, convert them to lists - if params is not None and not isinstance(params, (list, tuple)): - params = list(params) - try: - args = [(':arg%d' % i) for i in range(len(params[0]))] - except (IndexError, TypeError): + if not params: # No params given, nothing to do return None - # cx_Oracle wants no trailing ';' for SQL statements. For PL/SQL, it - # it does want a trailing ';' but not a trailing '/'. However, these - # characters must be included in the original query in case the query - # is being passed to SQL*Plus. - if query.endswith(';') or query.endswith('/'): - query = query[:-1] - query = convert_unicode(query % tuple(args), self.charset) - formatted = [self._format_params(i) for i in params] + # uniform treatment for sequences and iterables + params_iter = iter(params) + query, firstparams = self._fix_for_params(query, next(params_iter)) + # we build a list of formatted params; as we're going to traverse it + # more than once, we can't make it lazy by using a generator + formatted = [firstparams]+[self._format_params(p) for p in params_iter] self._guess_input_sizes(formatted) try: return self.cursor.executemany(query, diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 324adfd97b..92dbf354ae 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -101,6 +101,7 @@ class DatabaseFeatures(BaseDatabaseFeatures): has_bulk_insert = True can_combine_inserts_with_and_without_auto_increment_pk = False autocommits_when_autocommit_is_off = True + supports_paramstyle_pyformat = False @cached_property def uses_savepoints(self): diff --git a/django/db/models/query.py b/django/db/models/query.py index b0ce25f5b5..27a87a3f65 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1445,7 +1445,10 @@ class RawQuerySet(object): yield instance def __repr__(self): - return "" % (self.raw_query % tuple(self.params)) + text = self.raw_query + if self.params: + text = text % (self.params if hasattr(self.params, 'keys') else tuple(self.params)) + return "" % text def __getitem__(self, k): return list(self)[k] diff --git a/docs/ref/databases.txt b/docs/ref/databases.txt index a648ac1709..4e5f136e2e 100644 --- a/docs/ref/databases.txt +++ b/docs/ref/databases.txt @@ -623,6 +623,14 @@ If you're getting this error, you can solve it by: SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will have no effect. +"pyformat" parameter style in raw queries not supported +------------------------------------------------------- + +For most backends, raw queries (``Manager.raw()`` or ``cursor.execute()``) +can use the "pyformat" parameter style, where placeholders in the query +are given as ``'%(name)s'`` and the parameters are passed as a dictionary +rather than a list. SQLite does not support this. + .. _sqlite-connection-queries: Parameters not quoted in ``connection.queries`` diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 2c1fffd8cd..1fd98e1271 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -337,6 +337,12 @@ Minor features default) to allow customizing the :attr:`~django.forms.Form.prefix` of the form. +* Raw queries (``Manager.raw()`` or ``cursor.execute()``) can now use the + "pyformat" parameter style, where placeholders in the query are given as + ``'%(name)s'`` and the parameters are passed as a dictionary rather than + a list (except on SQLite). This has long been possible (but not officially + supported) on MySQL and PostgreSQL, and is now also available on Oracle. + Backwards incompatible changes in 1.6 ===================================== diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt index 2ec31a4988..7437d51d28 100644 --- a/docs/topics/db/sql.txt +++ b/docs/topics/db/sql.txt @@ -166,9 +166,17 @@ argument to ``raw()``:: >>> lname = 'Doe' >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname]) -``params`` is a list of parameters. You'll use ``%s`` placeholders in the -query string (regardless of your database engine); they'll be replaced with -parameters from the ``params`` list. +``params`` is a list or dictionary of parameters. You'll use ``%s`` +placeholders in the query string for a list, or ``%(key)s`` +placeholders for a dictionary (where ``key`` is replaced by a +dictionary key, of course), regardless of your database engine. Such +placeholders will be replaced with parameters from the ``params`` +argument. + +.. note:: Dictionary params not supported with SQLite + + Dictionary params are not supported with the SQLite backend; with + this backend, you must pass parameters as a list. .. warning:: @@ -181,14 +189,21 @@ parameters from the ``params`` list. **Don't.** - Using the ``params`` list completely protects you from `SQL injection + Using the ``params`` argument completely protects you from `SQL injection attacks`__, a common exploit where attackers inject arbitrary SQL into your database. If you use string interpolation, sooner or later you'll fall victim to SQL injection. As long as you remember to always use the - ``params`` list you'll be protected. + ``params`` argument you'll be protected. __ http://en.wikipedia.org/wiki/SQL_injection +.. versionchanged:: 1.6 + + In Django 1.5 and earlier, you could pass parameters as dictionaries + when using PostgreSQL or MySQL, although this wasn't documented. Now + you can also do this whem using Oracle, and it is officially supported. + + .. _executing-custom-sql: Executing custom SQL directly diff --git a/tests/backends/tests.py b/tests/backends/tests.py index c6cad56ec1..c1a26df7fc 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -456,13 +456,24 @@ class SqliteChecks(TestCase): class BackendTestCase(TestCase): def create_squares_with_executemany(self, args): + self.create_squares(args, 'format', True) + + def create_squares(self, args, paramstyle, multiple): cursor = connection.cursor() opts = models.Square._meta tbl = connection.introspection.table_name_converter(opts.db_table) f1 = connection.ops.quote_name(opts.get_field('root').column) f2 = connection.ops.quote_name(opts.get_field('square').column) - query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2) - cursor.executemany(query, args) + if paramstyle=='format': + query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2) + elif paramstyle=='pyformat': + query = 'INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)' % (tbl, f1, f2) + else: + raise ValueError("unsupported paramstyle in test") + if multiple: + cursor.executemany(query, args) + else: + cursor.execute(query, args) def test_cursor_executemany(self): #4896: Test cursor.executemany @@ -491,6 +502,35 @@ class BackendTestCase(TestCase): self.create_squares_with_executemany(args) self.assertEqual(models.Square.objects.count(), 9) + @skipUnlessDBFeature('supports_paramstyle_pyformat') + def test_cursor_execute_with_pyformat(self): + #10070: Support pyformat style passing of paramters + args = {'root': 3, 'square': 9} + self.create_squares(args, 'pyformat', multiple=False) + self.assertEqual(models.Square.objects.count(), 1) + + @skipUnlessDBFeature('supports_paramstyle_pyformat') + def test_cursor_executemany_with_pyformat(self): + #10070: Support pyformat style passing of paramters + args = [{'root': i, 'square': i**2} for i in range(-5, 6)] + self.create_squares(args, 'pyformat', multiple=True) + self.assertEqual(models.Square.objects.count(), 11) + for i in range(-5, 6): + square = models.Square.objects.get(root=i) + self.assertEqual(square.square, i**2) + + @skipUnlessDBFeature('supports_paramstyle_pyformat') + def test_cursor_executemany_with_pyformat_iterator(self): + args = iter({'root': i, 'square': i**2} for i in range(-3, 2)) + self.create_squares(args, 'pyformat', multiple=True) + self.assertEqual(models.Square.objects.count(), 5) + + args = iter({'root': i, 'square': i**2} for i in range(3, 7)) + with override_settings(DEBUG=True): + # same test for DebugCursorWrapper + self.create_squares(args, 'pyformat', multiple=True) + self.assertEqual(models.Square.objects.count(), 9) + def test_unicode_fetches(self): #6254: fetchone, fetchmany, fetchall return strings as unicode objects qn = connection.ops.quote_name diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py index e404c8b065..7242b8309b 100644 --- a/tests/raw_query/tests.py +++ b/tests/raw_query/tests.py @@ -3,7 +3,7 @@ from __future__ import absolute_import from datetime import date from django.db.models.query_utils import InvalidQuery -from django.test import TestCase +from django.test import TestCase, skipUnlessDBFeature from .models import Author, Book, Coffee, Reviewer, FriendlyAuthor @@ -123,10 +123,27 @@ class RawQueryTests(TestCase): query = "SELECT * FROM raw_query_author WHERE first_name = %s" author = Author.objects.all()[2] params = [author.first_name] - results = list(Author.objects.raw(query, params=params)) + qset = Author.objects.raw(query, params=params) + results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) + self.assertIsInstance(repr(qset), str) + + @skipUnlessDBFeature('supports_paramstyle_pyformat') + def testPyformatParams(self): + """ + Test passing optional query parameters + """ + query = "SELECT * FROM raw_query_author WHERE first_name = %(first)s" + author = Author.objects.all()[2] + params = {'first': author.first_name} + qset = Author.objects.raw(query, params=params) + results = list(qset) + self.assertProcessed(Author, results, [author]) + self.assertNoAnnotations(results) + self.assertEqual(len(results), 1) + self.assertIsInstance(repr(qset), str) def testManyToMany(self): """ -- cgit v1.3 From 5caced89e0ac2f942b68bc5f163d156a42880f16 Mon Sep 17 00:00:00 2001 From: Baptiste Mispelon Date: Fri, 28 Jun 2013 09:43:14 +0200 Subject: Fixed missing slash in reusable apps tutorial. --- docs/intro/reusable-apps.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/intro/reusable-apps.txt b/docs/intro/reusable-apps.txt index 4247b45238..879cda913a 100644 --- a/docs/intro/reusable-apps.txt +++ b/docs/intro/reusable-apps.txt @@ -67,7 +67,7 @@ After the previous tutorials, our project should look like this:: admin.py models.py static/ - polls + polls/ images/ background.gif style.css -- cgit v1.3 From 27cf7ec864318daf5957fa0e65c04f7a260ee1c8 Mon Sep 17 00:00:00 2001 From: Jacob Kaplan-Moss Date: Fri, 28 Jun 2013 08:56:45 -0500 Subject: Master is now pre-1.7. --- django/__init__.py | 2 +- docs/conf.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/django/__init__.py b/django/__init__.py index 5a1c74efa7..b8077e17fa 100644 --- a/django/__init__.py +++ b/django/__init__.py @@ -1,4 +1,4 @@ -VERSION = (1, 6, 0, 'alpha', 1) +VERSION = (1, 7, 0, 'alpha', 0) def get_version(*args, **kwargs): # Don't litter django/__init__.py with all the get_version stuff. diff --git a/docs/conf.py b/docs/conf.py index feff99b6f4..0c35e935e6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -55,7 +55,7 @@ copyright = 'Django Software Foundation and contributors' # built documents. # # The short X.Y version. -version = '1.6' +version = '1.7' # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version @@ -71,7 +71,7 @@ else: release = django_release() # The "development version" of Django -django_next_version = '1.6' +django_next_version = '1.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -- cgit v1.3 From 94f420ef48eb87e6fb6f1fe66d68a11e1b8b939d Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Fri, 28 Jun 2013 16:27:07 +0200 Subject: Updated FAQ entry about python 3 --- docs/faq/install.txt | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'docs') diff --git a/docs/faq/install.txt b/docs/faq/install.txt index 5a4cab94cf..5ca7a471c8 100644 --- a/docs/faq/install.txt +++ b/docs/faq/install.txt @@ -77,15 +77,12 @@ Django version Python versions Can I use Django with Python 3? ------------------------------- -Django 1.5 introduces experimental support for Python 3.2.3 and above. However, -we don't yet suggest that you use Django and Python 3 in production. +Yes, you can! -Python 3 support should be considered a "preview". It's offered to bootstrap -the transition of the Django ecosystem to Python 3, and to help you start -porting your apps for future Python 3 compatibility. But we're not yet -confident enough to promise stability in production. +Django 1.5 introduced experimental support for Python 3.2.3 and above. -Our current plan is to make Django 1.6 suitable for general use with Python 3. +As of Django 1.6, Python 3 support is considered stable and you can safely use +it in production. See also :doc:`/topics/python3`. Will Django run under shared hosting (like TextDrive or Dreamhost)? ------------------------------------------------------------------- -- cgit v1.3 From 8809da67a22117c0010607b801e5c31ec7bdc735 Mon Sep 17 00:00:00 2001 From: Claude Paroz Date: Fri, 28 Jun 2013 16:38:55 +0200 Subject: Updated FAQ to reflect official Python 3 support --- docs/faq/install.txt | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) (limited to 'docs') diff --git a/docs/faq/install.txt b/docs/faq/install.txt index 5ca7a471c8..d221f93d02 100644 --- a/docs/faq/install.txt +++ b/docs/faq/install.txt @@ -16,9 +16,8 @@ How do I get started? What are Django's prerequisites? -------------------------------- -Django requires Python, specifically Python 2.6.5 - 2.7.x. No other Python -libraries are required for basic Django usage. Django 1.5 also has -experimental support for Python 3.2.3 and above. +Django requires Python, specifically Python 2.6.5 - 2.7.x, or 3.2.3 and above. +No other Python libraries are required for basic Django usage. For a development environment -- if you just want to experiment with Django -- you don't need to have a separate Web server installed; Django comes with its @@ -43,7 +42,7 @@ Do I lose anything by using Python 2.6 versus newer Python versions, such as Pyt ---------------------------------------------------------------------------------------- Not in the core framework. Currently, Django itself officially supports -Python 2.6 (2.6.5 or higher) and 2.7. However, newer versions of +Python 2.6 (2.6.5 or higher), 2.7, 3.2.3 or higher. However, newer versions of Python are often faster, have more features, and are better supported. If you use a newer version of Python you will also have access to some APIs that aren't available under older versions of Python. @@ -51,12 +50,9 @@ aren't available under older versions of Python. Third-party applications for use with Django are, of course, free to set their own version requirements. -All else being equal, we recommend that you use the latest 2.x release -(currently Python 2.7). This will let you take advantage of the numerous -improvements and optimizations to the Python language since version 2.6. - -Generally speaking, we don't recommend running Django on Python 3 yet; see -below for more. +All else being equal, we recommend that you use the latest 2.7 or 3.x release. +This will let you take advantage of the numerous improvements and optimizations +to the Python language since version 2.6. What Python version can I use with Django? ------------------------------------------ -- cgit v1.3