5.7 Redirect After a POST
This commit is contained in:
parent
8bfd695ece
commit
deceab97c3
@ -19,12 +19,12 @@ class HomePageTest(TestCase):
|
|||||||
def test_can_save_a_POST_request(self):
|
def test_can_save_a_POST_request(self):
|
||||||
response = self.client.post('/', data={'item_text': 'A new list item'})
|
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
|
self.assertEqual(Item.objects.count(), 1)
|
||||||
new_item = Item.objects.first() # same as doing objects.all()[0]
|
new_item = Item.objects.first()
|
||||||
self.assertEqual(new_item.text, 'A new list item') # check that the item's text is correct
|
self.assertEqual(new_item.text, 'A new list item')
|
||||||
|
|
||||||
self.assertIn('A new list item', response.content.decode())
|
self.assertEqual(response.status_code, 302)
|
||||||
self.assertTemplateUsed(response, 'home.html')
|
self.assertEqual(response['location'], '/')
|
||||||
|
|
||||||
def test_only_saves_items_when_necessary(self):
|
def test_only_saves_items_when_necessary(self):
|
||||||
self.client.get('/')
|
self.client.get('/')
|
||||||
|
@ -1,18 +1,13 @@
|
|||||||
from django.http.request import HttpRequest
|
from django.http.request import HttpRequest
|
||||||
from django.http.response import HttpResponse
|
from django.http.response import HttpResponse
|
||||||
from django.shortcuts import render
|
from django.shortcuts import redirect, render
|
||||||
|
|
||||||
from lists.models import Item
|
from lists.models import Item
|
||||||
|
|
||||||
# Create your views here
|
# Create your views here
|
||||||
def home_page(request):
|
def home_page(request):
|
||||||
if request.method == 'POST':
|
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=request.POST['item_text'])
|
||||||
Item.objects.create(text=new_item_text) # .object.create is shortcut for creating a new Item, without needing to call .save()
|
return redirect('/')
|
||||||
else:
|
|
||||||
new_item_text = ''
|
|
||||||
|
|
||||||
return render(request=request, template_name='home.html', context={
|
|
||||||
'new_item_text': request.POST.get('item_text', ''),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
return render(request=request, template_name='home.html')
|
Loading…
x
Reference in New Issue
Block a user