Search code examples
pythondjangocheckboxdjango-tables2

How to add a checkbox column in django_tables2


I am trying to add a checkbox column so that the users of the interface can select rows and move them. How do I add the checkbox column to a table? I have found the checkboxcolumn.py file in django, but I do not know how to properly implement it into my project.

Here is my code for reference.

tables.py

import django_tables2 as tables
from .models import Model60Mm, Model120Mm, Model122Mm

class Table60mm(tables.Table):
    class Meta:
        model = Model60Mm
        template_name = 'django_tables2/bootstrap.html'

class Table120mm(tables.Table):
    class Meta:
        model = Model120Mm
        template_name = 'django_tables2/bootstrap.html'

class Table122mm(tables.Table):
    class Meta:
        model = Model122Mm
        template_name = 'django_tables2/bootstrap.html'

class DateTable60mm(tables.Table):
    shot_time = tables.Column()
    class Meta:
        model = Model60Mm
        order_by = '-shot_name'
        template_name = 'django_tables2/bootstrap.html'

views.py

from django.shortcuts import render
from django_tables2 import RequestConfig
from django_tables2 import SingleTableView
from .models import Model60Mm, Model120Mm, Model122Mm
from .tables import Table60mm, Table120mm, Table122mm

def home(request):
    return render(request, 'database/home.html')

def sixty(request):
    table = Table60mm(Model60Mm.objects.all())
    table.paginate(page=request.GET.get('page', 1), per_page=25)
    return render(request, 'database/sixty.html', {'table': table})

def onetwenty(request):
    table = Table120mm(Model120Mm.objects.all())
    table.paginate(page=request.GET.get('page', 1), per_page=25)
    return render(request, 'database/onetwenty.html', {'table': table})

def onetwentytwo(request):
    table = Table122mm(Model122Mm.objects.all())
    table.paginate(page=request.GET.get('page', 1), per_page=25)
    return render(request, 'database/onetwentytwo.html', {'table': table})

def sixtydate(request):
    table = Table60mm(Model60Mm.objects.all(), order_by='-shot_time')
    table.paginate(page=request.GET.get('page', 1), per_page=25)
    return render(request, 'database/sixtydate.html', {'table': table})

sixty.html template for 60mm table

{% extends 'database/home.html' %}
{% load render_table from django_tables2 %}
{% block content %}
    <h1>60MM Data Table</h1>
    {% render_table table %}
{% endblock content %}

Solution

  • I suggest to have a read at https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html

    Using the mentioned Accessors and the CheckBoxColumn comes with django-tables2, you may try something like:

    class DateTable60mm(tables.Table):
        your_field = table2.CheckBoxColumn(accessor='your_field ')
    

    And then, the your_field will be rendered as checkboxes in your pages.