我正在尝试使用序列化程序在Django Rest Framework中上传CSV文件。
下面的图像提供了包含模型,视图和序列化器的代码以及当我尝试提交CSV文件时控制台输出的图像。
在我验证print(serializer.initial_data)之前,在验证序列化程序之前,序列化程序内部有一个文件,但是一旦序列化程序进行验证,它说没有文件提交。
models.py
class InventoryFile(models.Model):
shop = models.ForeignKey(Shop,on_delete=models.CASCADE)
shop_inventory = models.FileField(upload_to='inventory/')
serializers.py
class InventoryFile_Serializer(serializers.ModelSerializer):
class Meta:
model = InventoryFile
fields = ('shop_inventory',)
views.py
class InvertoryUpload(APIView):
serializer_class = InventoryFile_Serializer
parser_classes = [ MultiPartParser,FormParser ]
def post(self,request):
try:
serializer = InventoryFile_Serializer(data=request.data)
print(serializer.initial_data)
if serializer.is_valid():
print(serializer.data)
return Response("Done")
else:
print(serializer.errors)
return Response("Not Done")
except Exception as e:
return Response(str(e))
输出
System check identified no issues (0 silenced).
January 30, 2019 - 11:22:06
Django version 2.1, using settings 'hoplet.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
<QueryDict: {'inventory': [<InMemoryUploadedFile: MOCK_DATA_2.csv (application/vnd.ms-excel)>]}>
{'shop_inventory': [ErrorDetail(string='No file was submitted.', code='required')]}
[30/Jan/2019 11:22:18] "POST /uploadinv HTTP/1.1" 200 10
答案 0 :(得分:0)
请求中的文件的密钥名称为inventory
,而序列化程序正在寻找的密钥名称为is shop_inventory
。它们应该是相同的。更改其中之一,它应该可以工作。
答案 1 :(得分:0)
Please try in this way
urls.py
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^upload_file', InvertoryUpload.as_view())
]
models.py
class InventoryFile(models.Model):
shop = models.ForeignKey(Shop,on_delete=models.CASCADE)
shop_inventory = models.FileField(upload_to='inventory/')
views.py
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.generics import CreateAPIView
class InvertoryUpload(CreateAPIView):
serializer_class = InventoryFile_Serializer
parser_classes = [ MultiPartParser, FormParser ]
serializers.py
class InventoryFile_Serializer(serializers.ModelSerializer):
class Meta:
model = InventoryFile
fields = ('shop_inventory','shop')