Brandon
Brandon

Reputation: 19

Django return class attribute based on object status in database

I am new to django and trying to learn. Looking to see if there is a better way to produce the result wanted. See my example below:

application_list.html - Table Data

<tbody>
    {% for app in applications %}
    <tr>
      <th style="text-align: left;"><a href="{{ app.get_absolute_url }}">{{ app.username }}</a></th>
      <td>{{ app.desired_username }}</td>
      <td>{{ app.created }}</td>
      {% if app.application_status_id == 1 %}
      <td><span class="badge bg-secondary">{{ app.application_status }}</span></td>
      {% elif app.application_status_id == 2 %}
      <td><span class="badge bg-success">{{ app.application_status }}</span></td>
      </td>
      {% endif %}

    </tr>
    {% endfor %}
  </tbody>

See here I am setting the class based on the value of the application status id from the database.

Instead of having multiple if statements, is it possible to place this code elsewhere to process and return the class attribute back to line?

I have tried looking at views.py for the application, but unable to determine how this works. My thoughts were to create a function to return a context value for application_list.

application/views.py

def application_list(request):
    """List of all applications"""
    template = 'application/application_list.html'
    applications = Application.objects.all()
    
    context = {
        'applications': applications,
    }
    
    return render(request, template, context)

Upvotes: 1

Views: 54

Answers (1)

dacx
dacx

Reputation: 844

There are multiple ways to solve this; I'll show you two common ones.

  1. Place the if statement inside the css class tag:
<td><span class="badge {% if app.application_status == 1 %}bg-primary{% elif app.application_status == 2 %}bg-secondary{% endif %}">{{ app.application_status }}</span></td>
      

  1. Add a property to your model:
# views.py

from django.db import models

class Application(models.Model):
    application_status_id = ...

    @property
    def css_background_class(self):
        if self.application_status_id == 1:
            return 'bg-primary'
        elif self.application_status_id == 2:
            return 'bg-secondary'

and use it in the template like so:

<td><span class="badge {{app.css_background_class}}">{{ app.application_status }}</span></td>
      

Upvotes: 0

Related Questions