use*_*729 17 testing django action admin request
我是django的新手,我在测试app_model_changelist下拉列表中的自定义操作(例如actions = ['mark_as_read'])时遇到了问题,它与标准的"删除选中"相同.自定义操作在管理视图中工作,但我不知道如何在我的模拟请求中调用它,我知道我需要发布数据但是如何说我想对我发布的数据执行"mark_as_read"操作?
我想反转changelist url并发布查询集,以便"mark_as_read"动作函数处理我发布的数据.
change_url = urlresolvers.reverse('admin:app_model_changelist')
response = client.post(change_url, <QuerySet>)
Run Code Online (Sandbox Code Playgroud)
cat*_*ran 27
只需action
使用操作名称传递参数即可.
response = client.post(change_url, {'action': 'mark_as_read', ...})
Run Code Online (Sandbox Code Playgroud)
已检查的项目作为_selected_action
参数传递.所以代码将是这样的:
fixtures = [MyModel.objects.create(read=False),
MyModel.objects.create(read=True)]
should_be_untouched = MyModel.objects.create(read=False)
#note the unicode() call below
data = {'action': 'mark_as_read',
'_selected_action': [unicode(f.pk) for f in fixtures]}
response = client.post(change_url, data)
Run Code Online (Sandbox Code Playgroud)
以下是如何使用登录和所有内容来完成此操作,这是一个完整的测试用例:
from django.test import TestCase
from django.urls import reverse
from content_app.models import Content
class ContentModelAdminTests(TestCase):
def setUp(self):
# Create some object to perform the action on
self.content = Content.objects.create(titles='{"main": "test tile", "seo": "test seo"}')
# Create auth user for views using api request factory
self.username = 'content_tester'
self.password = 'goldenstandard'
self.user = User.objects.create_superuser(self.username, 'test@example.com', self.password)
def shortDescription(self):
return None
def test_actions1(self):
"""
Testing export_as_json action
App is content_app, model is content
modify as per your app/model
"""
data = {'action': 'export_as_json',
'_selected_action': [self.content._id, ]}
change_url = reverse('admin:content_app_content_changelist')
self.client.login(username=self.username, password=self.password)
response = self.client.post(change_url, data)
self.client.logout()
self.assertEqual(response.status_code, 200)
Run Code Online (Sandbox Code Playgroud)
只需修改以使用您的模型和自定义操作并运行测试即可。
更新:如果您获得 302,您可能需要follow=True
在self.client.post()
.
这是我的工作:
data = {'action': 'mark_as_read', '_selected_action': Node.objects.filter(...).values_list('pk', flat=True)}
response = self.client.post(reverse(change_url), data, follow=True)
self.assertContains(response, "blah blah...")
self.assertEqual(Node.objects.filter(field_to_check=..., pk__in=data['_selected_action']).count(), 0)
Run Code Online (Sandbox Code Playgroud)
与接受的答案相比,有一些注意事项:
values_list
而不是列表理解来获取ID。follow=True
因为期望发布成功会导致重定向 归档时间: |
|
查看次数: |
5219 次 |
最近记录: |