Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: django-tables2 DetailView CBV won't display 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")

A 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 a 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 gets the object pk and everything, but doesn't send just the one single object to populate the table. I know it gets the object because object.id and object.nickname both display correctly. I know it is possible to display only a specific object because I have another app in the same project that displays only one object if you click the link that takes you to DetailView (the template of which I borrowed to re-create with my Account models). But it will only display a table of ALL the objects.

I can put up request data if necessary. I can promise you I have seen the object in the template context, and indeed it must be or object.id would not work. What's the trick for django-tables2? Apparently I already did it once!

like image 632
mastachimp Avatar asked Sep 26 '22 10:09

mastachimp


1 Answers

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

In this case, you want a list with only one item, the object from the DetailView.

def get_table_data(self):
    return [self.object]
like image 138
Alasdair Avatar answered Sep 30 '22 08:09

Alasdair