5.2 Processing a POST Request on the Server

This commit is contained in:
Jason Zhu 2020-11-08 16:24:07 +11:00
parent 9c102d7add
commit 81b586ac07
2 changed files with 9 additions and 7 deletions

View File

@ -1,3 +1,4 @@
from django.http import response
from django.test import TestCase from django.test import TestCase
from django.urls import resolve from django.urls import resolve
from django.http import HttpRequest from django.http import HttpRequest
@ -10,11 +11,10 @@ class HomePageTest(TestCase):
found = resolve('/') found = resolve('/')
self.assertEqual(found.func, home_page) self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self): def test_uses_home_template(self):
""" response = self.client.get('/')
1. Instead of manually creating HttpRequest object and calling view function to get response, pass in URL to `self.client.get()` and get response directly self.assertTemplateUsed(response, 'home.html')
3. `.assertTemplateUsed` is the test method that Django Test Case provides. it checks whether template was used to render a response
"""
response = self.client.get('/') #1 def test_can_save_a_POST_request(self):
self.assertTemplateUsed(response, 'home.html') #3 response = self.client.post('/', data={'item_text': 'A new list item'})
self.assertIn('A new list item', response.content.decode())

View File

@ -8,4 +8,6 @@ def home_page(request):
Using render function to take a request and name of the template to render Using render function to take a request and name of the template to render
""" """
if request.method == 'POST':
return HttpResponse(request.POST['item_text'])
return render(request, 'home.html') return render(request, 'home.html')