8

I have declared a table and want to fetch the row's value which is checked using checkboxfield. Any help, how can i write this event in my views so that everytime I select a row and hit submit button, it returns the row's values.Code goes like this:

    class mytables(tables.Table):
          new_database = tables.CheckBoxColumn()
          student =tables.Column(accessor='Student')
          Class = tables.Column(accessor='class')

And in my templates a submit button.

Karan
  • 239
  • 4
  • 13

1 Answers1

23

You need to choose a suitable value for the CheckBoxColumn. Generally if you're displaying a queryset, you'll use the pk of each object for the CheckBoxColumn. In your case this would look like:

class EnrollmentTable(tables.Table):
    selection = tables.CheckBoxColumn(accessor='pk')
    student = tables.Column()
    class = tables.Column()

Then you'll need to render the table within a form, so that the user can submit the form, e.g.:

<form action="/someurl/" method="post">
    {% load render_tables from django_tables2 %}
    {% render_table table %}
    <input type="submit"/>
</form>

Then you'll need a view hooked up to /someurl/. In your case the view will need to look at the POST variable selection:

def someview(request):
    if request.method == "POST":
        pks = request.POST.getlist("selection")
        selected_objects = SomeModel.objects.filter(pk__in=pks)
        # do something with selected_objects
    else:
        # ...
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
  • Thanks for the solution but While debugging I see that pks is a list containing only None as in if i select two rows then [u'None,u'None]...any thoughts about that? – Karan Jun 04 '12 at 08:23
  • That sounds like you're not using saved model objects as your table data. – bradley.ayers Jun 05 '12 at 01:26
  • Thanks a lot i forgot to include the pk value in queryset. Its working fine. – Karan Jun 05 '12 at 07:38
  • Fantastic answer. It seems strange that this isn't included in the official documentation – tomnl Apr 25 '17 at 10:08