jieter / django-tables2

django-tables2 - An app for creating HTML tables
https://django-tables2.readthedocs.io/en/latest/
Other
1.86k stars 426 forks source link

feature: CRUD example table #923

Open markdoerr opened 1 year ago

markdoerr commented 1 year ago

Hi,

how would I do some edit/ updates / delete on a column with nice bootstrap icons in one columns ? Could you please add an example, where it is shown how to use the new linkify feature to do update / edit / delete operations on a certain column of a table - including the corresponding view ?

Thanks a lot for you help !

Alexandre-petitjean commented 6 months ago

A quick solution (not perfect at all) is to make a custom Column. The column get the data for the actions from a method in the object class.

First the table definition :

class ConsumableTable(tables.Table):
    actions = ActionsColumn(accessor="get_actions", verbose_name="Actions")

Then the Column definition

class ActionsColumn(tables.Column):

    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)
        self.orderable = False

    def render(self, value):
        result = '<div class="d-flex flex-row justify-content-evenly">'
        for k, v in value.items():
            match k:
                case "detail":
                    result += f'<a href="{v}"><i class="bi bi-eye"></i></a>'
                case "edit":
                    result += f'<a href="{v}"><i class="bi bi-pencil"></i></a>'
                case "delete":
                    # delete is the only action to have a list in value.
                    result += f'<a href="#" class="btn-delete-{v[0]}" data-form-url="{v[1].get_delete_url()}" data-id="{v[1].id}" data-extra="{v[1]}"><i class="bi bi-trash"></i></a>'
        return format_html(result + "</div>")

And the data provider for the column

    def get_actions(self):
        return {
            "detail": self.get_absolute_url(),
            "edit": self.get_edit_url(),
            "delete": ["consumable", self]
        }