我正在Django REST ViewSets上进行Django Unittesting
在一个端点中,它可以接收字段和图像
这是models.py
class CarData(AbstractSoftModelController):
front_photo = models.ImageField(upload_to=RandomFileName('upload/cars'),
blank=True,
verbose_name=_('Front photo'))
brand = models.CharField(max_length=255, db_index=True, verbose_name=_('Brand'))
model = models.CharField(max_length=255, db_index=True, verbose_name=_('Model'))
color = models.CharField(max_length=255,
blank=True,
db_index=True,
verbose_name=_('Color'))
viewsets.py
class CarDataViewSet(viewsets.ModelViewSet):
serializer_class = CarDataSerializer
permission_classes = (IsAuthenticated,)
filter_class = CarDataFilter
queryset = CarData.objects.filter(license_plate__alive=True, license_plate__isnull=False)
serializers.py
class CarDataSerializer(ModelControllerSerializer):
class Meta:
model = CarData
exclude = EXCLUDE_COMMON_FIELDS
extra_kwargs = {
}
我想用图像测试POST
到这个端点。
class CarDataViewSetTestCase(APITestCase):
def setUp(self):
mommy.make(User, _quantity=1, username='sivabudh')
mommy.make(CarData, _quantity=3,
brand='Ferrari',
color='black')
mommy.make(LicensePlate, _quantity=3)
self.client.force_login((User.objects.get(username='sivabudh')))
def test_create(self):
file_path = str(settings.ROOT_DIR.path('static_files/images/logo-eneos.png'))
with open(file_path, "r", encoding='utf-8', errors='ignore') as fp:
data = {
'brand': 'Ferrari',
'model': 'LaFerrari Aperta',
'color': 'Red',
'license_plate': LicensePlate.objects.first().id,
'front_photo': fp
}
response = self.client.post(
reverse('api:car-list'),
data,
content_type='application/x-www-form-urlencoded'
)
import pdb; pdb.set_trace()
assert 200 == response.status_code
错误是:
(Pdb) response.data
["{'brand': ['This field is required.'], 'model': ['This field is required.'], 'license_plate': ['This field is required.']}"]
我的尝试:
然后我稍微更改了标题
content_type='multipart/form-data'
我得到了{'detail': 'Multipart form parse error - Invalid boundary in multipart: None'}
我哪里错了?