我想在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 %}
答案 0 :(得分: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 %}