[英]Test Django admin form
I'd like to test adding a custom document file form in my application in the admin panel.我想在管理面板的应用程序中测试添加自定义文档文件表单。 Unfortunately django documentation is quite obscure about this one.不幸的是,django 文档对此非常晦涩。
This is my model:这是我的模型:
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)
This is my test:这是我的测试:
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)
I'd like to get 200 response while posting the form with shown data.我希望在发布包含显示数据的表单时获得 200 条回复。 For some reason response.status_code gives 404 and response.reason_phrase gives 'Not Found'.出于某种原因,response.status_code 给出 404,response.reason_phrase 给出“未找到”。 Is it possible the problem lies in the directory?问题可能出在目录中吗?
You have to log the client in :您必须登录客户端:
c = Client()
c.login(username='your_username', password='your_password')
response = c.post(change_url, data)
The most correct way to define change_url
is using reverse()
.定义change_url
最正确的方法是使用reverse()
。 You can browse the docs to find the correct way to do this.您可以浏览文档以找到执行此操作的正确方法。 For example:例如:
change_url = reverse('admin:docrepo_document_add')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.