How to add File Upload with Python Django Rest Framework?

To add File Upload with Python Django Rest Framework, we can add a FileField into our model.

For instance, we write

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')

to create the ExperimentViewSet in Django that gets the file from self.request.FILES.get('file') in pre_save.

And then we create the Experiment model with the FileField that we use with ExperimentViewSet.

And then we add the ExperimentSerializer that has the samplesheet in the fields.