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



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

错误

我看过Django的文档&尝试在我的HTML模板中使用default标记,但没有成功。该值在models.py 中命名为image_ingredients

我如何才能让用户将ImageField留空?

这是我的代码:

型号.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

视图.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>
{% if recipe.image_ingredients %}<img src="{{ recipe.image_ingredients.url }}">{% endif %}
<p>{{ recipe.ingredients }}</p>

最新更新