【问题标题】:Django and Bootstrap: prevent warning box from appearing if there is an empty stringDjango和Bootstrap:防止出现空字符串时出现警告框
【发布时间】:2021-09-20 13:17:08
【问题描述】:

如果有message,我正在使用 Django 模板和 Bootstrap 呈现红色警报框。代码是:

views.py

else:
    return render(request, 'auctions/listing.html', {
        'listing': listing,
        'form': BidForm(),
        'message': '',
        'comments': listing.comments.all()
    })

listing.html

<div>
    <p>Starting Bid: {{ listing.starting_bid}}</p>
    <p>Current Bid: {{ listing.price }}</p>
    <div class="alert alert-danger" role="alert" style="display: inline-block;">
        {{ message }}
    </div>
</div>

如果没有消息(即空字符串),则呈现红色警告框,这看起来很明智和直观。但是,当我从 views.py 中删除 message 时,红色警告框仍然呈现。

    else:
        return render(request, 'auctions/listing.html', {
            'listing': listing,
            'form': BidForm(),
#            'message': '',
            'comments': listing.comments.all()
        })

我在这里做错了什么?谢谢!

【问题讨论】:

    标签: django bootstrap-4 django-views django-templates


    【解决方案1】:

    只检查message是否不为空,然后只显示。

    此代码仅在 message 不为空时显示警报。

    {% if message %}
    <div class="alert alert-danger" role="alert" style="display: inline-block;">
            {{ message }}
        </div>
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2010-11-06
      相关资源
      最近更新 更多