Search code examples
javascriptjqueryhtmldjangodjango-simple-history

Substituting values in a HTML table?


I am making a HTML table to display boxes (in a stockroom) that have been added, removed and changed. The headings are denoting the owner of the box, the type of change that has occurred and the new content of the box.

Im using Django for my backend.

Can I translate the values in the 'Type of Change' into English words rather than the symbols (~, - and +)? I am using Django simple-history to record changes to my models and it returns these symbols. I would like my table to read 'Changed', 'Removed' and 'Added' in place of '~', '-' and '+' respectfully.

My table

This is the view.py:

def dashboard(request):
    box_content_history = Box.history.all().order_by('-history_date')
    return render(request, 'main_app/dashboard.html', {""box_content_history":box_content_history})

The HTML:

<table id="asset_changes_datatable">
    <thead>
        <tr>
            <th>Owner</th>
            <th>Type of Change</th>
            <th>Box Contents</th>
        </tr>
   </thead>
   <tbody>
   {% for item in box_content_history %}
        <tr>
            <td>{{ item.project_assigned_to }}</td>
            <td>{{ item.history_type }}</td>
            <td>{{ item.box_contents }}</td>
        </tr>
   {% endfor %}
   </tbody>
</table>

Solution

  • As already mentioned in the comments just change {{ item.history_type }} to {{ item.get_history_type_display }} in the template.

    What is this sorcery and where does it come from?

    This is actually vanilla django functionality and is explained in the Model instance reference.

    For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

    Why does it work for the history_type field of django-simple-history?

    Quite simple: The history_type field has the aforementioned choices set. I checked that by looking at their source code on github.

    "history_type": models.CharField(
        max_length=1,
        choices=(("+", _("Created")), ("~", _("Changed")), ("-", _("Deleted"))),
    ),