Reputation: 1224
I am new to Django Rest Framework. I have a Django model with a file field.
class MyClass(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
file = models.FileField(blank=False, null=True, use_url=True)
class MyClassSerializer(serializers.ModelSerializer):
class Meta(object):
model = MyClass
exclude = []
class MyClassView(generics.RetrieveUpdateDestroyAPIView):
queryset = MyClass.objects.all()
serializer_class = MyClassSerializer
Take two MyClass
instances A & B. From my front-end, I'd like to send a PUT request to copy the file of Instance A to model B.
Therefore I first make a GET requests which returns instance A with a file URL (ex: `{..., file: 'http://myserver.com/file.pdf')). I then send a PUT request to update instance B with that URL but I get the following error:
The submitted data was not a file. Check the encoding type on the form.
For performance reasons I don't want the file to be downloaded and uploaded again. Any idea how to serialize the filed field to make it accept an url of another file on my server ?
Upvotes: 0
Views: 1763
Reputation: 4208
You can use URLField
in your serializer then in your put request you can send the link instead.
If the file is hosted on your own server and there is a pk available for it, you can use that instead.
Example:
class MyClassSerializer(ModelSerializer):
file_url= URLField(required=True)
class Meta:
model = MyClass
fields = ('file_url',)
def update(self, instance, validated_data):
link = validated_data.get('file_url')
# and whatever you need to do like download the file or ...
Also you can handle the file in your validations and then pass it for update.
Something like this:
def validate_file_url(self, value):
if value:
#download the file and return it.
return value
Basically anytime you need to do something out of the box, considering adding your own fields and validate them as you wish and use it as you need.
Upvotes: 1