Search code examples
djangodjango-modelsimagefield

Django - How to return to default image after users delete their uploaded image?


So I originally had the user create a post in admin and be able to leave image field blank and Django would set a default image.

My problem is; If a user uploads an image, then deletes the image in admin, I get an error: The 'image' attribute has no file associated with it. when accessing solo.html in browser.

How can I make the default image reappear and specifically come from static folder? Static folder location

My code:

settings.py

STATIC_URL = '/static/'

STATIC_DIRS = os.path.join(BASE_DIR, 'static')

models.py

# FIXME: If default image is changed to user's upload but then deleted. Make default image reappear.
# Recipe Field
class Recipe(models.Model):
    title = models.CharField(max_length=200)


    image = models.ImageField(upload_to='recipes/images/', blank=True)
    def get_image(self):
        if not self.image:
            return f'{settings.STATIC_URL}default.png'
        return self.image.url

solo.html

<h2>{{ recipe.title }}</h2>
<h3>{{ recipe.category }}</h3>
<h3>{{ recipe.meal }}</h3>



<img src="{{ recipe.image.url }}">

I'm just starting with Django so I apologize in advance if it's all a mess. Thank you in advance!


Solution

  • What's happening is that the file itself is being deleted, but recipe.image is not being set to None.