M.Izzat M.Izzat - 1 year ago 114
Python Question

Jinja2 - display delete button in particular html table row if condition is true

I'm trying to create an if else condition using jinja2 where only table row with the status

will display a delete button beside it. But I'm having trouble figuring it out because all the data in the table is displayed in a
for loop
so if the condition is true and all row have the delete button and vice versa.

Any help is much appreciated

Below is my code :


class Leave(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+')
type = models.ForeignKey(LeavesType, on_delete=models.CASCADE, related_name='+')
status = (('cancelled', 'Cancelled'),
('taken', 'Taken'),
('pending_approval', 'Pending Approval'),
('scheduled', 'Scheduled'),
('weekend', 'Week End'),
('public_holiday', 'Public holiday'),
status = models.CharField(max_length=50, choices=status, default='pending_approval')


def my_leaves_view(request):
leaves_log = Leave.objects.all().filter(employee=request.user.profile.employee.id)
context = {'leaves_log': leaves_log}
return render(request, 'hrm/employee/details/my_leaves.html', context)


<table id="Log" class="display table table-hover table-responsive leaves-table">
<th class="small text-muted text-uppercase"><strong>Leave Type</strong></th>
<th class="small text-muted text-uppercase"><strong>Status</strong></th>
<th class="small text-muted text-uppercase"><strong></strong></th>
{% for field in leaves_log %}
<td><img class="media-object img-circle status-icon-size" src="/media/dashboard/ui/file_status/{{field.status}}.png" style="display: inline-block; height: 24px; margin-right: 10px;">{{field.status}}</td>
<td><div class="btn-group">
{% if field.status == 'pending_approval' or 'scheduled'%}
<button type="button" class="btn btn-default btn-xs dropdown-toggle active" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Action <span class="caret"></span>
<ul class="dropdown-menu dropdown-menu-right">
<li onclick="delete_leaves();">
<a href="/hrm/employee/{{field.id}}/delete/" onclick="return confirm('Are you sure you want to delete this item?');">
<i class="fa fa-fw fa-trash text-gray-lighter m-r-1"></i>Withdraw
{% else %}
{% endif %}

Answer Source

You are not using the or operator correctly. It is used to separate two boolean values, so you can imagine

{% if field.status == 'pending_approval' or 'scheduled' %}

being interpreted as

{% if bool(field.status == 'pending_approval') or bool('scheduled') %}

and bool('any non-empty string') is always True

The correct syntax is

{% if field.status == 'pending_approval' or field.status == 'scheduled' %}


{% if field.status in ['pending_approval', 'scheduled'] %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download