I have this model in my django app:
class Person(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(blank=True, upload_to='images', default='default/static/image/here')
def __str__(self):
return self.name
When making a Person object, if left empty, the "image" is set to a default value, but later, if the user decides to remove his image, his image will no longer be set to default but to NULL instead. How can I make it so that whenever image is NULL again, it automatically brings back the default value?
When image will be changed, ImageField won't be Null. You can just set default image. if user want to remove his image, default image again will appear.
You can modify the save method that checks if the ImageField is Null
class Person(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(blank=True, upload_to='images', default='default/static/image/here')
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if not self.image: #here
self.image = 'default/static/image/here'
super(Person, self).save(*args, **kwargs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.