From e171a83b1516a3a2a393a5300527af1aab21c213 Mon Sep 17 00:00:00 2001 From: Alex Morozov Date: Tue, 10 Nov 2015 16:06:59 +0300 Subject: [PATCH] Fixed #25548 -- Prevented FormView.form_invalid() from discarding its form argument. --- django/views/generic/edit.py | 2 +- tests/generic_views/test_edit.py | 7 +++++++ tests/generic_views/urls.py | 2 ++ tests/generic_views/views.py | 10 ++++++++++ 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/django/views/generic/edit.py b/django/views/generic/edit.py index 6223129786..644110f9ea 100644 --- a/django/views/generic/edit.py +++ b/django/views/generic/edit.py @@ -83,7 +83,7 @@ class FormMixin(ContextMixin): If the form is invalid, re-render the context data with the data-filled form and errors. """ - return self.render_to_response(self.get_context_data()) + return self.render_to_response(self.get_context_data(form=form)) def get_context_data(self, **kwargs): """ diff --git a/tests/generic_views/test_edit.py b/tests/generic_views/test_edit.py index df5dab3f79..5b4bec96af 100644 --- a/tests/generic_views/test_edit.py +++ b/tests/generic_views/test_edit.py @@ -71,6 +71,13 @@ class BasicFormTests(TestCase): res = self.client.post('/contact/', {'name': "Me", 'message': "Hello"}) self.assertRedirects(res, '/list/authors/') + def test_late_form_validation(self): + """ + A form can be marked invalid in the form_valid() method (#25548). + """ + res = self.client.post('/late-validation/', {'name': "Me", 'message': "Hello"}) + self.assertFalse(res.context['form'].is_valid()) + class ModelFormMixinTests(SimpleTestCase): def test_get_form(self): diff --git a/tests/generic_views/urls.py b/tests/generic_views/urls.py index 365e23ff32..1a65277477 100644 --- a/tests/generic_views/urls.py +++ b/tests/generic_views/urls.py @@ -65,6 +65,8 @@ urlpatterns = [ # FormView url(r'^contact/$', views.ContactView.as_view()), + url(r'^late-validation/$', + views.LateValidationView.as_view()), # Create/UpdateView url(r'^edit/artists/create/$', diff --git a/tests/generic_views/views.py b/tests/generic_views/views.py index be8a769b7b..e5ed1e2971 100644 --- a/tests/generic_views/views.py +++ b/tests/generic_views/views.py @@ -307,3 +307,13 @@ class NonModelDetail(generic.DetailView): class ObjectDoesNotExistDetail(generic.DetailView): def get_queryset(self): return Book.does_not_exist.all() + + +class LateValidationView(generic.FormView): + form_class = ContactForm + success_url = reverse_lazy('authors_list') + template_name = 'generic_views/form.html' + + def form_valid(self, form): + form.add_error(None, 'There is an error') + return self.form_invalid(form)