[Answered ]-How to add default image in django rest?

1👍

You can specify the default image on your Model, like this:

class Profile(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30,blank=True)
    dp = models.ImageField(upload_to = '/media/images/dp/',blank=True, default= '/media/images/dp/default.jpg', null=True, blank=True)

So, when you create the model, if you not send the dp image, the django will use the default value.

1👍

I personally like to keep my model fields as “lean” as possible, and “fatten” them up on the properties for easy changes without having to alter database tables.

With that said, I would recommend creating a property on your model to check for a profile picture uploaded by users, otherwise show the default one. Also, I would make your upload location a function for the same ease of alterations.

def upload_location(filename):
    return "media/images/dp/{}".format(filename)

class Profile(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30,blank=True)
    dp = models.ImageField(upload_to=upload_location', null=True, blank=True)

    @property
    def default_picture(self):
        if self.dp:
            return "{}{}".format(settings.MEDIA_URL, self.dp)
        return '/media/images/dp/default.jpg'
👤jape

Leave a comment