5.7 Redirect After a POST

This commit is contained in:
Jason Zhu 2020-11-09 11:57:23 +11:00
parent 8bfd695ece
commit deceab97c3
2 changed files with 10 additions and 15 deletions

View File

@ -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('/')

View File

@ -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')