Display Relevant Records From Many To Many In Django-tables2
Solution 1:
You can get the request
object from self.context
. So if you only need request.user
, that's one way to do it.
classOwnedTable(tables.Table):
roles = tables.Column(empty_values=())
def render_roles(self):
user = self.context["request"].user
...
Otherwise, @mariodev's solution works.
Solution 2:
It seems like there's no way of using auth user without some overriding.
You can override __init__
for our table class like this:
classOwnedTable(tables.Table):
def__init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(OwnedTable, self).__init__(*args, **kwargs)
then, inside view, you call table with user
argument, like so
table = OwnedTable(Person.objects.all(), user=request.user)
now you can use self.user
inside render_roles
method to refer to the currently logged in user.
Solution 3:
Another solution is shown on https://github.com/bradleyayers/django-tables2/issues/156, which worked for me after some adjustments for my setup.
Given that a Person would have an M2M to Contacts, and you want to display all contacts for that Person in django-tables2, then the following would do:
classPersonTable(tables.Table):
person_contacts = tables.Column(accessor="contacts", verbose_name="Contacts")
defrender_person_contacts(self, value, table):
clist = ""
cfirst = True
conts = list(value.all())
for c in conts:
ifnot cfirst:
clist += "<br />"else:
cfirst = Falseprint c.id
uri = reverse('cont_detail', kwargs={'pk': c.id})
clist += '<a href="' + uri + '">' + c.name + '</a>' + ' (' + c.relation + ')'return mark_safe(clist)
You basically add a column with a non-existent name, set the accessor to the M2M field name, then call render_<newly_added_column>
where you obtain what you need from value
.
Post a Comment for "Display Relevant Records From Many To Many In Django-tables2"