Show user's group in django tables2

602 views Asked by At

I'm using the default django models ( User and Group ) and I'm trying to display the user's group in a table rendered with django tables2.

The table is as follows:

class UserTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor="pk",
        attrs={"th__input": {"onclick": "toggleall(this)"}}, orderable=False)
    username = tables.LinkColumn('edituser', args=[A('pk')])
    first_name = tables.Column()
    last_name = tables.Column()
    group = tables.Column(accessor='user.groups.group_id')

    class Meta:
        template = 'django_tables2/bootstrap.html'
        attrs = {'class': 'table table-bordered table-striped table-hover'}
        sequence = ('selection','username', 'first_name', 'last_name', 'group')

Thank for helping

1

There are 1 answers

0
iOReK On BEST ANSWER

I was able to find a solution:

class UserTable(tables.Table):
  selection = tables.CheckBoxColumn(accessor="pk", attrs={"th__input": {"onclick": "toggleall(this)"}}, orderable=False)
  username = tables.LinkColumn('edituser', args=[A('pk')])
  groups = tables.Column(empty_values=())
  class Meta:
      model = User
      exclude = ('id', 'password', 'is_active', 'is_staff','date_joined', 'last_login', 'is_superuser')
      template = 'django_tables2/bootstrap.html'
      attrs = {'class': 'table table-bordered table-striped table-hover'}
      sequence = ('selection','username', 'first_name', 'last_name')

  def render_groups(self, record):
      if record.groups.all():
          return ', '.join([group.name for group in record.groups.all()])
      return '-'

render_groups return the list of all in which the user is part of