Skip to main content
 首页 » 编程设计

python之测试 Django 管理表单

2024年08月21日31小虾米

我想在管理面板的应用程序中测试添加自定义文档文件表单。不幸的是,django 文档对此非常晦涩。

这是我的模型:

class Document(models.Model): 
    pub_date = models.DateTimeField('date published') 
    title = models.CharField(max_length=255) 
    description = models.TextField() 
    pdf_doc = models.FileField(upload_to=repo_dir, max_length=255) 

这是我的测试:

from django.test import TestCase 
from django.test import Client 
from django.utils import timezone 
from datetime import datetime, timedelta 
 
class DocumentAdminFormTest(TestCase): 
 
    def test_add_document_form(self): 
        client = Client() 
        change_url = 'admin/docrepo/document/add/' 
        today = datetime.today() 
        filepath = u'/filepath/to/some/pdf/' 
        data = {'title': 'TEST TITLE', 
                'description': 'TEST DESCRIPTION',  
                'pub_date0': '2000-01-01', 
                'pub_date1': '00:00:00', 
                'pdf_doc': filepath, 
                } 
        response = client.post(change_url, data) 
        print('REASON PHRASE: ' + response.reason_phrase) 
        self.assertIs(response.status_code, 200) 

我希望在发布包含显示数据的表单时获得 200 条回复。出于某种原因,response.status_code 给出 404,response.reason_phrase 给出“未找到”。问题可能出在目录上吗?

请您参考如下方法:

你必须 log the client in :

c = Client() 
c.login(username='your_username', password='your_password') 
response = c.post(change_url, data) 

定义change_url 的最正确方法是使用reverse()。你可以browse the docs找到正确的方法来做到这一点。例如:

change_url = reverse('admin:docrepo_document_add')