[Django]-Django Rest Framework โ€“ Downloading files on server

4๐Ÿ‘

โœ…

A better way of doing the same thing will be to create Your own serializer field

from django.core.validators import URLValidator
from django.core.files.base import ContentFile

from rest_framework import serializers

from urllib.request import urlretrieve

class FileUrlField(serializers.FileField):
    def to_internal_value(self, data):
        try:
            URLValidator()(data)
        except ValidationError as e:
            raise ValidationError('Invalid Url')

        # download the contents from the URL
        file, http_message = urlretrieve(data)
        file = File(open(file, 'rb'))
        return super(FileUrlField, self).to_internal_value(ContentFile(file.read(), name=file.name))

and then Use it in your serializer

class MySerializer(serializers.ModelSerializer):
    file = FileUrlField()
    class Meta:
        model = MyModel

However i am Not tested it but should work.

๐Ÿ‘คSatyajeet

Leave a comment