From deceab97c33854edb6a9ceb65c22bac765e8ede2 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Mon, 9 Nov 2020 11:57:23 +1100 Subject: [PATCH] 5.7 Redirect After a POST --- src/lists/tests.py | 12 ++++++------ src/lists/views.py | 13 ++++--------- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/lists/tests.py b/src/lists/tests.py index 0baafab..44e7101 100644 --- a/src/lists/tests.py +++ b/src/lists/tests.py @@ -19,12 +19,12 @@ class HomePageTest(TestCase): def test_can_save_a_POST_request(self): response = self.client.post('/', data={'item_text': 'A new list item'}) - self.assertEqual(Item.objects.count(), 1) # check that one new Item has been saved to the database - new_item = Item.objects.first() # same as doing objects.all()[0] - self.assertEqual(new_item.text, 'A new list item') # check that the item's text is correct - - self.assertIn('A new list item', response.content.decode()) - self.assertTemplateUsed(response, 'home.html') + self.assertEqual(Item.objects.count(), 1) + new_item = Item.objects.first() + self.assertEqual(new_item.text, 'A new list item') + + self.assertEqual(response.status_code, 302) + self.assertEqual(response['location'], '/') def test_only_saves_items_when_necessary(self): self.client.get('/') diff --git a/src/lists/views.py b/src/lists/views.py index 34f1ac4..d5e89eb 100644 --- a/src/lists/views.py +++ b/src/lists/views.py @@ -1,18 +1,13 @@ from django.http.request import HttpRequest from django.http.response import HttpResponse -from django.shortcuts import render +from django.shortcuts import redirect, render from lists.models import Item # Create your views here def home_page(request): if request.method == 'POST': - new_item_text = request.POST['item_text'] # use new_item_text to either hold POST contents or empty string - Item.objects.create(text=new_item_text) # .object.create is shortcut for creating a new Item, without needing to call .save() - else: - new_item_text = '' - - return render(request=request, template_name='home.html', context={ - 'new_item_text': request.POST.get('item_text', ''), - }) + Item.objects.create(text=request.POST['item_text']) + return redirect('/') + return render(request=request, template_name='home.html') \ No newline at end of file