I am using Django Rest Framework and AngularJs to upload a file. My view file looks like this:
JavaScript
x
15
15
1
class ProductList(APIView):
2
authentication_classes = (authentication.TokenAuthentication,)
3
def get(self,request):
4
if request.user.is_authenticated():
5
userCompanyId = request.user.get_profile().companyId
6
products = Product.objects.filter(company = userCompanyId)
7
serializer = ProductSerializer(products,many=True)
8
return Response(serializer.data)
9
10
def post(self,request):
11
serializer = ProductSerializer(data=request.DATA, files=request.FILES)
12
if serializer.is_valid():
13
serializer.save()
14
return Response(data=request.DATA)
15
As the last line of post method should return all the data, I have several questions:
- how to check if there is anything in
request.FILES
? - how to serialize file field?
- how should I use parser?
Advertisement
Answer
Use the FileUploadParser, it’s all in the request. Use a put method instead, you’ll find an example in the docs :)
JavaScript
1
8
1
class FileUploadView(views.APIView):
2
parser_classes = (FileUploadParser,)
3
4
def put(self, request, filename, format=None):
5
file_obj = request.FILES['file']
6
# do some stuff with uploaded file
7
return Response(status=204)
8