Search code examples
djangodjango-modelsdjango-templatesimagefield

Django - How to leave ImageField blank if user doesn't upload image


I'm trying to build a recipe app that allows users to upload images and save recipes in a list. The problem I'm facing is when the user doesn't upload an image, I get error: attribute has no file associated with it.

Error

I've looked in Django documentation & tried using default tag in my HTML template with no success. The value is named image_ingredients in models.py

How could I make it so the user can just leave the ImageField empty?

Here is my code:

models.py

# Recipe Field

class Recipe(models.Model):
    title = models.CharField(max_length=200)
# TODO: Add default image if image is left blank
    image = models.ImageField(upload_to='recipes/images/', blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE,)
    daily_meals = ['Breakfast', 'Brunch', 'Elevenses', 'Lunch', 'Tea', 'Supper', 'Dinner']
    meal = models.ForeignKey(Meal, limit_choices_to={'name__in': daily_meals}, on_delete=models.CASCADE,)

    image_ingredients = models.ImageField(upload_to='recipes/images/', null=True, blank=True)

    ingredients = models.TextField(blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

views.py

# Solo recipe with instructions

def solo(request, recipe_id):
    recipe = get_object_or_404(Recipe, pk=recipe_id)
    return render(request, 'recipes/solo.html', {'recipe':recipe})

solo.html

<h4>Ingredients</h4>
<img src="{{ recipe.image_ingredients.url }}">
<p>{{ recipe.ingredients }}</p>

Solution

  • You can render the image only when there is an image_ingredients item present, for example:

    <h4>Ingredients</h4>
    {% if recipe.image_ingredients %}<img src="{{ recipe.image_ingredients.url }}">{% endif %}
    <p>{{ recipe.ingredients }}</p>