[Answer]-How to display a FileField that doesn't exist on the model – Django Rest Framework

1👍

You’ll need to define a function on the model that returns the URL (it needs to be somehow related to your object obviously)

def get_file_url(self):
    return settings.STORAGE_LOCATION + 'some/path/' + str(self.pk) + '.png'

And then you can use that in your serializer, like:

upload_file = serializers.FileField(source='get_file_url')

To save the file during POST, you’ll need to override the create method of your serializer, like:

def create(self, validated_data):
    file = validated_data['upload_file']
    # save file code here
    del validated_data['upload_file']
    return XYZ.objects.create(**validated_data)

Leave a comment