【问题标题】:Django - How to leave ImageField blank if user doesn't upload imageDjango - 如果用户不上传图像,如何将 ImageField 留空
【发布时间】:2020-03-20 18:51:15
【问题描述】:

我正在尝试构建一个食谱应用程序,允许用户上传图像并将食谱保存在列表中。 我面临的问题是当用户不上传图片时,我收到错误: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>

【问题讨论】:

  • 只需在此周围使用{% if recipe.image_ingredients %} ... {% endif %}
  • 非常感谢,成功了!您可以将其写在答案中以将您的答案标记为解决方案吗?

标签: django django-models django-templates imagefield


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2015-02-22
    • 1970-01-01
    • 2016-04-23
    • 2019-09-04
    • 1970-01-01
    • 2012-02-08
    相关资源
    最近更新 更多