Selaa lähdekoodia

Add a URL for creating a new list via POST

david 5 vuotta sitten
vanhempi
commit
b3fe636962
5 muutettua tiedostoa jossa 21 lisäystä ja 10 poistoa
  1. 1 1
      SCRATCHPAD.txt
  2. 1 1
      lists/templates/home.html
  3. 13 4
      lists/tests.py
  4. 5 4
      lists/views.py
  5. 1 0
      superlists/urls.py

+ 1 - 1
SCRATCHPAD.txt

@@ -7,5 +7,5 @@
 
 + Adjust model so that items are associated with different lists
 + Add unique URLs for each list
-+ Add a URL for creating a new list via POST
+- Add a URL for creating a new list via POST
 + Add URLs for adding a new item to an existing list via POST

+ 1 - 1
lists/templates/home.html

@@ -4,7 +4,7 @@
     </head>
     <body>
         <h1>Start a new To-Do list</h1>
-        <form method="POST" action="/">
+        <form method="POST" action="/lists/new">
             <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
             {% csrf_token %}
         </form>

+ 13 - 4
lists/tests.py

@@ -36,10 +36,6 @@ class HomePageTest(TestCase):
         self.assertEqual(response.status_code, 302)
         self.assertEqual(response['location'], '/lists/the-only-list/')
 
-    def test_only_saves_items_when_needed(self):
-        self.client.get('/')
-        self.assertEqual(Item.objects.count(), 0)
-
 class ListViewTest(TestCase):
 
     def test_uses_list_template(self):
@@ -73,3 +69,16 @@ class ItemModelTest(TestCase):
         second_item = saved[1]
         self.assertEqual(first_item.text, item1.text)
         self.assertEqual(second_item.text, item2.text)
+
+class NewListTest(TestCase):
+
+    def test_can_save_a_POST_request(self):
+        self.client.post('/lists/new', data={'item_text': 'A new list item'})
+        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('/lists/new', data={'item_text': 'A new list item'})
+        self.assertRedirects(response, '/lists/the-only-list/')

+ 5 - 4
lists/views.py

@@ -3,11 +3,12 @@ from django.shortcuts import render, redirect
 from lists.models import Item
 
 def home_page(request):
-    if request.method == 'POST':
-        Item.objects.create(text=request.POST['item_text'])
-        return redirect('/lists/the-only-list/')
     return render(request, 'home.html')
 
 def view_list(request):
     items = Item.objects.all()
-    return render(request, 'list.html', {'items': items})
+    return render(request, 'list.html', {'items': items})
+
+def new_list(request):
+    Item.objects.create(text=request.POST['item_text'])
+    return redirect('/lists/the-only-list/')

+ 1 - 0
superlists/urls.py

@@ -18,5 +18,6 @@ from lists import views
 
 urlpatterns = [
     url(r'^$', views.home_page, name='home'),
+    url(r'^lists/new$', views.new_list, name='new_list'),
     url(r'^lists/the-only-list/$', views.view_list,  name='view_list'),
 ]