I want to conditionally display fields of a form in django template. I use a current value of a choice field as follows. However I can not see this working as expected and nothing is rendered at all in the <p>
tag.
In the model:
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)
In the template:
{% 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 %}
Simply check with the defined value
PEN
. And I would recommend using an integer instead of a string,In the model:
template
Above solution is kinda hardcoded so instead of that use instance method .get_foo_display(),