Django: django-tables2 DetailView CBV does not display a single object

I have a table

import django_tables2 as tables from .models import Account from django_tables2.utils import A # alias for Accessor class AccountTable(tables.Table): nickname = tables.LinkColumn('accounts:detail', args=[A('pk')]) class Meta: model = Account attrs = {'class': 'table table-striped table-hover'} exclude = ("created", "modified", "destination") 

View:

 class DetailView(SingleTableMixin, generic.DetailView): template_name = 'accounts/account_detail.html' context_table_name = 'table' model = Account table_class = AccountTable context_object_name = object @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DetailView, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(object=self.object) context['title'] = 'Account Detail' context['pk'] = self.kwargs.get(self.pk_url_kwarg, None) return context 

And the template:

 <!DOCTYPE html> {% extends "accounts/base.html" %} {% load django_tables2 %} {% load render_table from django_tables2 %} <title>Account Detail</title> {% block content %} <br> <br> <h1>{{ object.id }} : {{object.nickname}}</h1> <div> {% render_table table %} </div> {% endblock %} 

It correctly receives the pk object and that's it, but does not send only one single object to populate the table. I know that it receives an object because the objects object.id and object.nickname are displayed correctly. I know that only a specific object can be displayed, because I have another application in the same project that displays only one object, if you click on the link that brings you to the DetailView (the template I borrowed to recreate using my account models). But it will only display a table of ALL objects.

If necessary, I can send request data. I can promise you that I saw the object in the context of the template, and indeed, it should be or object.id does not work. What is the trick for django-tables2? Apparently, I already did it once!

+5
source share
1 answer

You can override the get_table_data method of your view and return a list of objects that you want to display.

In this case, you need a list with only one item, an object from a DetailView .

 def get_table_data(self): return [self.object] 
+3
source

Source: https://habr.com/ru/post/1234334/


All Articles