Django學習系列15:把POST請求中的數據存入數據庫


要修改針對首頁中的POST請求的測試。希望視圖把新添加的待辦事項存入數據庫,而不是直接傳給響應。

為了測試這個操作,要在現有的測試方法test_can_save_a_post_request中添加3行新代碼

# lists/tests.py

    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)  # 1
        new_item = Item.objects.first()  # 2
        self.assertEqual(new_item.text, 'A new list item')  # 3
        
        self.assertIn('A new list item', response.content.decode())
        self.assertTemplateUsed(response, 'home.html')

代碼解析:

1、檢查是否把一個新Item對象存入數據庫,objects.count()是objects.all().count()的簡寫形式

2、objects.first()等價於objects.all()[0]

3、檢查待辦事項的文本是否正確。

再次運行測試

    self.assertEqual(Item.objects.count(), 1)  # 1
AssertionError: 0 != 1

修改一下視圖

from django.shortcuts import render
from lists.models import Item
from django.http import HttpResponse

# Create your views here.在這兒編寫視圖
def home_page(request):
    item = Item()
    item.text = request.POST.get('item_text', '')
    item.save()
    
    return render(request, 'home.html', {
        'new_item_text': request.POST.get('item_text', ''),
    })

單元測試……通過了。

審視一下前面的代碼,或許能發現一些明顯的問題或需要注意的:

1、不要每次請求都保存空白的待辦事項

2、post請求的測試太長

3、在表格中顯示多個待辦事項

4、支持多個清單!

 

代碼重構

解決單元測試一次只測試一件事,在現有代碼中添加一個斷言,定義一個新的測試方法

# lists/tests.py

class HomePageTest(TestCase):
  【……】
        
    def test_only_saves_items_when_necessary(self):
        self.client.get('/')
        self.assertEqual(Item.objects.count(), 0)

這個測試得到AssertionError: 1 != 0失敗

下面來修正這個問題,注意,雖然對視圖函數的邏輯改動幅度很小,但代碼實現方式有細微的變動。

from django.shortcuts import render
from lists.models import Item
from django.http import HttpResponse

# Create your views here.在這兒編寫視圖
def home_page(request):
    if request.method == 'POST':
        new_item_text = request.POST['item_text']  # 1
        Item.objects.create(text=new_item_text)  # 2
    else:
        new_item_text = ''  # 1

    return render(request, 'home.html', {
        'new_item_text': new_item_text,  # 1
    })

代碼解析:

#1 使用名為 new_item_text的變量,其值是POST請求中的數據,或者空字符串。

#2 .objects.create()是創建新Item對象的簡化方式,無需在調用.save()方法。

這樣重構后測試通過

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM