【发布时间】:2020-03-20 18:51:15
【问题描述】:
我正在尝试构建一个食谱应用程序,允许用户上传图像并将食谱保存在列表中。
我面临的问题是当用户不上传图片时,我收到错误:attribute has no file associated with it.
我查看了 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>
【问题讨论】:
-
只需在此周围使用
{% if recipe.image_ingredients %} ... {% endif %}。 -
非常感谢,成功了!您可以将其写在答案中以将您的答案标记为解决方案吗?
标签: django django-models django-templates imagefield