From fd4dcc2425c2b3be7eb1a4d3653b0081ab19d3c3 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Mon, 9 Nov 2020 12:18:41 +1100 Subject: [PATCH] 5.8 Rendering Items in the Template --- textbook/chap5.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/textbook/chap5.md b/textbook/chap5.md index 38546f1..d2e5913 100644 --- a/textbook/chap5.md +++ b/textbook/chap5.md @@ -337,4 +337,56 @@ So, separate the test code into two: self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], '/') +``` + +## 5.8 Rendering Items in the Template + +Now, both "Don't save blank items for every request" and "Code smell: POST test is too long?" are finished + +Target: "Display multiple item in the table" + +TDD step 1: create a UT to check + +```python + + def test_displays_all_list_items(self): + Item.objects.create(text="itemey 1") + Item.objects.create(text="itemey 2") + + response = self.client.get('/') + + self.assertIn('itemey 1', response.content.decode()) + self.assertIn('itemey 2', response.content.decode()) +``` + +Test will fail as `home.html` we still only allow one item in table + +```html + + +
1: {{ new_item_text }}
+``` + +Fix it by allow it to have iterating list. Django template syntax has a tag for iterating through a list `{% for .. in .. %}` + `% endfor %` + +```html + + {% for item in items %} + + {% endfor %} +
1: {{ item.text }}
+``` + +Also need pass items to template from home page view: + +```python +def home_page(request): + if request.method == 'POST': + Item.objects.create(text=request.POST['item_text']) + return redirect('/') + + items = Item.objects.all() # get objects from database (model) + return render(request=request, + template_name='home.html', + context={'items': items}) # pass items into template using render ``` \ No newline at end of file