Django restframework发送帖子数据从测试APIClient中断

时间:2016-12-05 21:24:29

标签: django python-3.x django-rest-framework

从APIClient数据发送时,

DoFn返回request.data.get('answers_ids')而不是str '2'。但是,当我从其他框架web-gui发送数据时,所有工作都可以。

使用:

  • django == 1.10.4
  • djangorestframework == 3.5.3

tests.py:

array ['1', '2']

views.py:

class ApiCompletePoll(APITestCase):
    def setUp(self):
        self.user = User.objects.create(
            username='123',
            password='123',
            email='123@123.ru'
        )
        self.client = APIClient()
        self.client.credentials(
             HTTP_AUTHORIZATION='Token ' + self.user.auth_token.key
        )

    def test_complete_poll(self):
        data = {'poll_id': 1, 'answers_ids': [1, 2]}     # SENT DATA
        self.client.post(reverse('complete-poll'), data)
        self.assertTrue(
            CompletedPoll.objects.filter(
                user=self.user, poll__id=data['poll_id']
            )
        )

输出:

@api_view(http_method_names=['post', ])
def update_or_create_user_answers(request):
    user = request.user
    poll_id = request.data.get('poll_id', 0)
    answers_ids = request.data.get('answers_ids', [])

    print(list(request.data.items()), request.data, answers_ids)    # GETTING DATA

1 个答案:

答案 0 :(得分:0)

要在QueryDict中检索已传递密钥的值列表,您需要使用.getlist()方法:

answers_ids = request.data.getlist('answers_ids', [])

这应输出:['1', '2']