代码之家  ›  专栏  ›  技术社区  ›  joe

测试上传Excel文件和JSONField Django REST

  •  2
  • joe  · 技术社区  · 9 年前

    我的 models.py 有3个字段。其中之一是 JSONField()

    attribute = JSONField(null=True, blank=True)  # Free to add any note to here
    type = models.CharField(max_length=30, choices=FileType.choices, default=FileType.zipcode)
    file = models.FileField(upload_to='import_files')
    

    JSONField(null=True, blank=True) 为了方便起见。

    def test_upload_and_process_data_complete_case(self):
        from soken_web.apps.imported_files.models import ImportFile
        with open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx', 'rb') as uploaded_file:
            data = {
                'attribute': {'author': 'Singh'},
                'type': ImportFile.FileType.zipcode,
                'file': uploaded_file
            }
            response = self.client.post(reverse('api:import_file-list'), data, format='multipart')
            response.render()
    
            self.assertEqual(status.HTTP_201_CREATED, response.status_code)
    

    JSONField


    当我用 杰森菲尔德

    AssertionError: Test data contained a dictionary value for key 'attribute', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case.
    

    然而,根据我的理解,我必须发布 multipart 因为 file .

    问题:
    杰森菲尔德 FileField

    参考:
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byte

    1 回复  |  直到 9 年前
        1
  •  4
  •   joe    9 年前

    在使用解析器之后。
    {"author": "Singh"} .
    因为web浏览器在 str

    def test_upload_and_process_data_complete_case(self):
        from soken_web.apps.imported_files.models import ImportFile
        with open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx', 'rb') as uploaded_file:
            data = {
                'attribute': '{"author": "Singh"}',
                'type': ImportFile.FileType.zipcode,
                'file': uploaded_file
            }
            response = self.client.post(reverse('api:import_file-list'), data, format='multipart')
            response.render()
    
            self.assertEqual(status.HTTP_201_CREATED, response.status_code)
    
    推荐文章