Django Rest Framework File Upload

Editor’s note:

  • This answer uses pre_save, which no longer exists in Django REST framework 3.0.
  • In a sufficiently new version of Django REST framework, MultiPartParser should be available by default, which allows uploading file with no special handling. See an answer below for an example.

I’m using the same stack and was also looking for an example of file upload, but my case is simpler since I use the ModelViewSet instead of APIView. The key turned out to be the pre_save hook. I ended up using it together with the angular-file-upload module like so:

# Django
class ExperimentViewSet(ModelViewSet):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializer

    def pre_save(self, obj):
        obj.samplesheet = self.request.FILES.get('file')

class Experiment(Model):
    notes = TextField(blank=True)
    samplesheet = FileField(blank=True, default="")
    user = ForeignKey(User, related_name="experiments")

class ExperimentSerializer(ModelSerializer):
    class Meta:
        model = Experiment
        fields = ('id', 'notes', 'samplesheet', 'user')
// AngularJS
controller('UploadExperimentCtrl', function($scope, $upload) {
    $scope.submit = function(files, exp) {
        $upload.upload({
            url: '/api/experiments/' + exp.id + "https://stackoverflow.com/",
            method: 'PUT',
            data: {user: exp.user.id},
            file: files[0]
        });
    };
});

Leave a Comment