django-tables2 add button per row
Asked Answered
S

2

18

I'm rendering a queryset with django-tables 2 but since the table is rendered at once I can't manage the following: Firstly, I should mention that the number of rows of the table is different with each queryset so I don't know the exact number of them in advance. What I need, is to have one button per row that loads the retrieved object inside the fields of a form. I render the table with the default way:

{% load render_table from django_tables2 %}
{% render_table table %} 

When I try to iterate over the rows of the tables I get the error 'table is not iterable'.

So how can I add one button per row?

Sayyid answered 30/8, 2012 at 7:34 Comment(0)
M
17

You can create in your table a template column, this will render something, a button for example:

class MyTables(tables.Table):
  ...
  my_column = tables.TemplateColumn(verbose_name=_('My Column'),
                                    template_name='app/my_column.html',
                                    orderable=False) # orderable not sortable

In the template my_column the row is in the variable record:

{{ record.my_field }}
Mccafferty answered 30/8, 2012 at 7:38 Comment(3)
Pretty close to that I needed! Triggered by your answer I found out: editable = tables.LinkColumn('edit_form',verbose_name='edit') Thank you for your instant answer!Sayyid
You said a button no a link... I'm sorry for my negativeMccafferty
I accepted your answer, I just mentioned that I used LinkColumn because it was an alternate solution that worked easier.Maybe I could be more clear, thanks anywaySayyid
S
2

Example: actions = TemplateColumn(template_code='<a href="{% url "review_detail" record.id %}" class="btn btn-success">View') this line of code adds a column to your table and adds the html content you want. To pass the id to your route, just call the "record" object

import django_tables2 as tables
from django_tables2 import TemplateColumn
from .models import Review, ReviewCategory, ReviewLog, ItemCategory


class ReviewTable(tables.Table):
    acciones = TemplateColumn(template_code='<a href="{% url "review_detail" record.id %}" class="btn btn-success">Ver</a>')
    class Meta:
        model = Review
        exclude = (
            'id',
            'assigned',
            'parent',
            'created_at',
            'updated_at'
            )
Sining answered 20/7, 2022 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.