5.6 Saving the POST to the Database
This commit is contained in:
parent
ac7a1a70e1
commit
8bfd695ece
3
.gitignore
vendored
3
.gitignore
vendored
@ -1 +1,2 @@
|
||||
.vscode
|
||||
.vscode
|
||||
**/migrations/**
|
@ -18,9 +18,18 @@ 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')
|
||||
|
||||
def test_only_saves_items_when_necessary(self):
|
||||
self.client.get('/')
|
||||
self.assertEqual(Item.objects.count(), 0)
|
||||
|
||||
class ItemModelTest(TestCase):
|
||||
|
||||
def test_saving_and_retrieving_items(self):
|
||||
|
@ -2,8 +2,17 @@ from django.http.request import HttpRequest
|
||||
from django.http.response import HttpResponse
|
||||
from django.shortcuts import 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', ''),
|
||||
})
|
||||
})
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user