Selaa lähdekoodia

Redirects after POST, shows all items, and only adds items if it's not blank!

david 5 vuotta sitten
vanhempi
commit
41929a63c9
3 muutettua tiedostoa jossa 33 lisäystä ja 7 poistoa
  1. 3 1
      lists/templates/home.html
  2. 22 2
      lists/tests.py
  3. 8 4
      lists/views.py

+ 3 - 1
lists/templates/home.html

@@ -9,7 +9,9 @@
             {% csrf_token %}
         </form>
         <table id="id_list_table">
-            <tr><td>1: {{ new_item_text }}</td></tr>
+            {% for item in items %}
+                <tr><td>{{forloop.counter}}: {{ item.text }}</td></tr>
+            {% endfor %}
         </table>
     </body>
 </html>

+ 22 - 2
lists/tests.py

@@ -26,8 +26,28 @@ class HomePageTest(TestCase):
 
     def test_can_save_POST_request(self):
         response = self.client.post('/', data={'item_text': 'A new list item'})
-        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')
+
+    def test_redirects_after_POST(self):
+        response = self.client.post('/', data={'item_text': 'A new list item'})
+        self.assertEqual(response.status_code, 302)
+        self.assertEqual(response['location'], '/')
+
+    def test_only_saves_items_when_needed(self):
+        self.client.get('/')
+        self.assertEqual(Item.objects.count(), 0)
+
+    def test_displays_all_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())
 
 class ItemModelTest(TestCase):
 

+ 8 - 4
lists/views.py

@@ -1,7 +1,11 @@
-from django.shortcuts import render
+from django.shortcuts import render, redirect
 #from django.http import HttpResponse
+from lists.models import Item
 
 def home_page(request):
-    return render(request, 'home.html', {
-        'new_item_text': request.POST.get('item_text', ''),
-    })
+    if request.method == 'POST':
+        Item.objects.create(text=request.POST['item_text'])
+        return redirect('/')
+
+    items = Item.objects.all()
+    return render(request, 'home.html', {'items': items})