diff --git a/.gitignore b/.gitignore index 600d2d3..be233cb 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.vscode \ No newline at end of file +.vscode +**/migrations/** \ No newline at end of file diff --git a/src/lists/tests.py b/src/lists/tests.py index fa5dbd6..0baafab 100644 --- a/src/lists/tests.py +++ b/src/lists/tests.py @@ -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): diff --git a/src/lists/views.py b/src/lists/views.py index e569739..34f1ac4 100644 --- a/src/lists/views.py +++ b/src/lists/views.py @@ -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', ''), - }) \ No newline at end of file + }) +