Fixed #26018 -- Prevented unecessary get_form() call in FormMixin.get_context_data().

Changed "dict.setdefault" to "if x in dict" pattern so that get_form() would not
be called unnecessarily, specifically in the case where FormMixin.form_invalid()
calls get_context_data() with the current form.
This commit is contained in:
Chris Cogdon 2015-12-30 13:22:58 -08:00 committed by Tim Graham
parent 7bc94b58bf
commit e429c5186c
4 changed files with 10 additions and 2 deletions

View File

@ -89,7 +89,8 @@ class FormMixin(ContextMixin):
"""
Insert the form into the context dict.
"""
kwargs.setdefault('form', self.get_form())
if 'form' not in kwargs:
kwargs['form'] = self.get_form()
return super(FormMixin, self).get_context_data(**kwargs)

View File

@ -13,7 +13,7 @@ Bugfixes
(:ticket:`25840`).
* Fixed a regression in ``FormMixin`` causing forms to be validated twice
(:ticket:`25548`).
(:ticket:`25548`, :ticket:`26018`).
* Fixed a system check crash with nested ``ArrayField``\s (:ticket:`25867`).

View File

@ -232,6 +232,7 @@ class UpdateViewTests(TestCase):
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_form.html')
self.assertEqual(res.context['view'].get_form_called_count, 1)
# Modification with both POST and PUT (browser compatible)
res = self.client.post('/edit/author/%d/update/' % a.pk,
@ -251,6 +252,7 @@ class UpdateViewTests(TestCase):
self.assertTemplateUsed(res, 'generic_views/author_form.html')
self.assertEqual(len(res.context['form'].errors), 1)
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
self.assertEqual(res.context['view'].get_form_called_count, 1)
def test_update_with_object_url(self):
a = Artist.objects.create(name='Rene Magritte')

View File

@ -147,10 +147,15 @@ class NaiveAuthorUpdate(generic.UpdateView):
class AuthorUpdate(generic.UpdateView):
get_form_called_count = 0 # Used to ensure get_form() is called once.
model = Author
success_url = '/list/authors/'
fields = '__all__'
def get_form(self, *args, **kwargs):
self.get_form_called_count += 1
return super(AuthorUpdate, self).get_form(*args, **kwargs)
class OneAuthorUpdate(generic.UpdateView):
success_url = '/list/authors/'