2

我想有条件地在 django 模板中显示表单的字段。我如下使用选择字段的当前值。但是我看不到它按预期工作,并且<p>标签中根本没有呈现任何内容。

在模型中:

PENDING = 'PEN'
CONFIRMED = 'CFM'
CANCELED = 'CAN'
CHOICE_BOOKING_STATUS = (
    (PENDING, 'Pending'),
    (CONFIRMED, 'Confirmed'),
    (CANCELED, 'Canceled'),
)

booking_status  = models.CharField(max_length=4,
                  choices=CHOICE_BOOKING_STATUS, 
                  default=PENDING)

在模板中:

{% extends parent_template|default:"booking/base_booking.html" %}
{% block title %}{{ block.super }} - Update booking Details{% endblock title %}

{% block header %}<h1>Update Booking</h1>{% endblock header %}

{% block content %}
<form action="{{ booking.get_update_url }}" method="POST">
    {% csrf_token %}
    <table>{{ form.as_table }}</table>
    <button type="submit" class="btn btn-primary">Update Details</button>
    <a href="{% url 'booking_list' %}">Cancel</a>

    {% if form.booking_status.value == CHOICE_BOOKING_STATUS.PENDING %}
        <p>Please make a payment to confirm booking.</p>
    {% endif %}

</form>
{% endblock content %}
4

1 回答 1

0

只需检查定义的值PEN。我建议使用整数而不是字符串,

在模型中:

PENDING = 1
CONFIRMED = 2
CANCELED = 3
CHOICE_BOOKING_STATUS = (
    (PENDING, 'Pending'),
    (CONFIRMED, 'Confirmed'),
    (CANCELED, 'Canceled'),
)

模板

{% if form.booking_status == 1 %}
    <p>Please make a payment to confirm booking.</p>
{% endif %}

上面的解决方案有点硬编码,所以不是使用实例方法.get_foo_display(),

{% if form.get_booking_status_display == 'Pending' %}
    <p>Please make a payment to confirm booking.</p>
{% endif %}
于 2021-05-30T13:18:06.517 回答