Using if condition with django choice field in templates

3.1k Views Asked by At

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 %}
1

There are 1 best solutions below

0
On

Simply check with the defined value PEN. And I would recommend using an integer instead of a string,

In the model:

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

template

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

Above solution is kinda hardcoded so instead of that use instance method .get_foo_display(),

{% if form.get_booking_status_display == 'Pending' %}
    <p>Please make a payment to confirm booking.</p>
{% endif %}