I am trying to include a conditional in my Django table, but I am having some issues finding the correct syntax to do so.
I have a boolean field in one of my models, and based on that value - I would like to render a different label_link
and callback url for that specific db record.
Here is the code I am using:
class Feature(BaseTable):
orderable = False
title_english = tables.Column()
featured_item = tables.Column()
if (featured_item == False):
actions = tables.TemplateColumn("""
{% url 'add_feature' pk=record.pk as url_ %}
{% label_link url_ 'Add to Features' %}
""", attrs=dict(cell={'class': 'span1'}))
else:
actions = tables.TemplateColumn("""
{% url 'remove_feature' pk=record.pk as url_ %}
{% label_link url_ 'Remove From Features' %}
""", attrs=dict(cell={'class': 'span1'}))
Now I am aware currently that this is just checking to see if the value exists - therefore always rendering the code under the else
statement.
I have been unable to find any documentation that covers this particular nuance of Django tables.
Note: I'm using Django 1.5 and Python 2.7
You can't put the if statement in the Feature
class - it is processed when the class is loaded, so you don't have access to the table data yet.
Inside the TemplateColumn
, you can access the current row of the table with record
, so you could move the logic there.
class Feature(BaseTable):
...
actions = tables.TemplateColumn("""
{% if not record.featured_item %}
{% url 'add_feature' pk=record.pk as url_ %}
{% label_link url_ 'Add to Features' %}
{% else %}
{% url 'remove_feature' pk=record.pk as url_ %}
{% label_link url_ 'Remove From Features' %}
{% endif %}
""", attrs=dict(cell={'class': 'span1'}))