How to add a photo to an object ? Django REST

Viewed 64

I have person model:

class Assistant(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    photo = models.ImageField(upload_to='photos/')

using Django REST how a photo was loaded from https://thispersondoesnotexist.com when creating a new assistant

I understand that you need to override the create method

how to do it in the best way?

ss

2 Answers
In Django Rest framework, you should send only the image URL. Here, I am creating image URL:

    from django.conf import settings

    class Assistant(models.Model):
        name = models.CharField(max_length=100)
        age = models.PositiveIntegerField()
        photo = models.ImageField(upload_to='photos/')

        @property
        def photo_url(self):
            return '%s%s' % (settings.HOST, self.photo.url) if self.photo else ''

On your Serializers.py:

    fields = ['name', 'age', 'photo_url']

class Assistant(models.Model):
    name = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    photo = models.URLField()

def get_remote_image(self):
    if self.image_url and not self.image_file:
        result = urllib.urlretrieve(self.image_url)
        self.image_file.save(
            os.path.basename(self.image_url),
            File(open(result[0]))
        )
    self.save()

You can override the default save() method to automatically invoke get_remote_image().

Related