Django - 如果用户不上传图片,如何将 ImageField 留空

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

我正在尝试构建一个允许用户上传图像并将食谱保存在列表中的食谱应用程序。 我面临的问题是当用户不上传图片时,出现错误:attribute has no file associated with it.

Error

我查看了 Django 文档并尝试在我的 HTML 模板中使用 default 标记但没有成功。 该值在 models.py

中命名为 image_ingredients

我怎样才能让用户可以将 ImageField 留空?

这是我的代码:

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>

只有当存在 image_ingredients 项时才能渲染图像,例如:

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