Django table with checkboxes

9,037 views
Skip to first unread message

Stanislav Nedelchev

unread,
Aug 1, 2011, 4:08:33 AM8/1/11
to Django users
Hi everyone,
I'm quite new to django and still learning.
But I face a problem that i can't solve.
I have the following very simple example.
Let say that I have one model for Books.

class Book(models.Model):
name = models.CharField(max_length=50,unique = True)
description = models.TextField(blank = True)
status = models.CharField(max_length=50,unique = True)
created_on = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name

If I search for all books for example.
I want to display table with result where first column is checkbox.
And if I check some books and hit button delete to be able to delete
them.
Also I what to have one input field or drop down where i can choose
"out of order" and click button update to change status of all slected
books to "out of order"
I'm reading the documentaion but I can't find how to do it.
I made one template where I generate table with results.But I can't
process checked books.
I added manually delete button and form in template.
But maybe I must use Forms instead.
Any hint or example how to acomplish this will be very usefull.


And sorry for my bad english.
Best regards

jocke khazad

unread,
Aug 1, 2011, 8:35:52 AM8/1/11
to django...@googlegroups.com
Hi Stanislav,

I would sugest to create your own form object instead of creating input tags directly in your template.

Read this page which also explains how to validate your form on the serverside:
https://docs.djangoproject.com/en/dev/topics/forms/

Use a boolean field to generate a checkbox.


Best regards,
Joakim




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.


Sophie Hume

unread,
Aug 1, 2011, 5:34:06 PM8/1/11
to Django users
Hi Stanislav

I think there's two ways you can do this... if you want to go down the
Forms route you actually want to be looking at Formsets [1], which
allow you to have a 'grid' of forms in a table with one row
representing each object.

If that seems like a steep learning curve to get your head around, and
you just want to try a quick-and-dirty approach, then you'd want a
loop in your template like {% for book in books %} ... {% endfor %}
then inside the loop build a <tr> for each item. If you make the first
tag in each row something like <select type="checkbox"
name="selected_book_id" value="{{ book.id }}" /> then follow it with
the other data fields, and have all of that wrapped in <form> ... </
form> tags, obviously, then you should be able to get the list of
checked options in your view by reading
request.POST.getlist(selected_book_id).

Hope this helps!
Sophie

[1] https://docs.djangoproject.com/en/dev/topics/forms/formsets/

On Aug 1, 1:35 pm, jocke khazad <khaz...@gmail.com> wrote:
> Hi Stanislav,
>
> I would sugest to create your own form object instead of creating input tags
> directly in your template.
>
> Read this page which also explains how to validate your form on the
> serverside:https://docs.djangoproject.com/en/dev/topics/forms/
>
> Use a boolean field to generate a checkbox.
>
> Best regards,
> Joakim
>

Stanislav Nedelchev

unread,
Aug 5, 2011, 12:11:03 PM8/5/11
to Django users
Sorry for my late response.
I found a way how to do it.
My fist mistake was that I creat a view fo deleting books.
And my form action is pointing this url.
Afrer I changed it to point to "."
But I search for more pythonic way.
This is how i get checked checkboxes;
try:
ch = []
if request.method == 'POST':
ch = request.POST.getlist('checkbox')
#assert False

This is part of my template.
<form name="bookform" action="." method="POST">
<td>
<input type="checkbox" name="checkbox" id="checkbox[]"
value={{ book.id }} />
</td>
input type="submit" value="Send me">
But I read that I can generate form from model and add checkbox.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
But at the moment I don't know how to implement it .
https://docs.djangoproject.com/en/dev/topics/forms/formsets/#manually-rendered-can-delete-and-can-order

On 2 Авг, 00:34, Sophie Hume <sophiehum...@gmail.com> wrote:
> Hi Stanislav
>
> I think there's two ways you can do this... if you want to go down the
> Forms route you actually want to be looking at Formsets [1], which
> allow you to have a 'grid' of forms in atablewith one row
> > > I want to displaytablewith result where first column is checkbox.
> > > And if I check some books and hit button delete to be able to delete
> > > them.
> > > Also I what to have one input field or drop down where i can choose
> > > "out of order" and click button update to change status of all slected
> > > books to "out of order"
> > > I'm reading the documentaion but I can't find how to do it.
> > > I made one template where I generatetablewith results.But I can't

Mikulas Peksa

unread,
Aug 5, 2016, 1:29:03 PM8/5/16
to Django users, sophie...@gmail.com
Hi Sophie,

I have just solved very similar problem. Thx you thousand times!!!

Mikuláš

Dne pondělí 1. srpna 2011 23:34:06 UTC+2 Sophie Hume napsal(a):

myskyroute

unread,
Oct 5, 2018, 7:26:33 AM10/5/18
to Django users
Hi,

I am actually looking for a quick help on the same issue. Trying to learn and create a delete button with checkbox's, 

Models:
class Customer(TimeStamp):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=100, blank=True, help_text="Long-form name (optional)")
    comments = models.TextField(blank=True)

    class Meta:
        # ordering = ['name']
        ordering = ['-id']


    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('App_CUS:customer_list')

Views.py:
class CustomerListView(ListView):
    queryset = Customer.objects.order_by('id')
    model = Customer
    paginate_by = 10
    context_object_name = 'customers'
    template_name = 'App_CUS/customer_list.html'

customer_list.html:
{% extends 'index.html' %}
{% load buttons %}

{% block content %}
<div class="pull-right">
    {% if perms.App_CUS.customer_add %}
        {% add_button 'App_CUS:customer_add' %}
        {% delete_button 'App_CUS:customer_delete' %}
    {% endif %}
</div>
<h1>{% block title %}Customers{% endblock %}</h1>
<div class="col-md-9">
<div class="table-responsive">
  <table class="table table-hover table-headings table-bordered">
    <thead>
      <tr>
        <th class="pk">
            <input class="toggle" title="Toggle all" type="checkbox">
        </th>
        <th>ID</th>
        <th>Customer Name</th>
        <th>Description</th>
       </tr>
    </thead>
    <tbody>
      {% for customer in customers %}
        <tr>
        <th class="pk">
            <input class="toggle" title="Toggle all" type="checkbox">
        </th>
          <td>{{ customer.pk }}</td>
          <td>{{ customer.name }}</td>
          <td>{{ customer.description }}</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
</div>
 
  {% if is_paginated %}
    <ul class="pagination">
      {% if page_obj.has_previous %}
        <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
      {% else %}
        <li class="disabled"><span>&laquo;</span></li>
      {% endif %}
      {% for i in paginator.page_range %}
        {% if page_obj.number == i %}
          <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
        {% else %}
          <li><a href="?page={{ i }}">{{ i }}</a></li>
        {% endif %}
      {% endfor %}
      {% if page_obj.has_next %}
        <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
      {% else %}
        <li class="disabled"><span>&raquo;</span></li>
      {% endif %}
    </ul>
  {% endif %}
{% endblock %}


Thanks,

nitesh rawat

unread,
Oct 27, 2018, 8:22:42 AM10/27/18
to Django users
Hi Stanislav,
I hope you get the solution to your problem, if you can , share the code.
Thanks.

Joel

unread,
Oct 27, 2018, 8:32:12 AM10/27/18
to django...@googlegroups.com
Very simple. Give each checkbox a unique name, and process the submit request by reading request.POST.getlist.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.

Joel

unread,
Oct 27, 2018, 8:38:50 AM10/27/18
to django...@googlegroups.com
Something like this:

@login_required
def batch_delete_bill_item(request):
if request.method == 'POST':
if request.POST.getlist('checks[]'):
selecteditems = request.POST.getlist('checks[]')
for sel in selecteditems:
item = get_object_or_404(billitem, code=sel)
try:
code = item.code

In the template you can have something like this:

{% for item in appointment_items %}
<input type="checkbox" name="checks[]" value="{{ item.pid }}" />
{% endfor %}

nitesh rawat

unread,
Oct 27, 2018, 9:50:45 AM10/27/18
to django...@googlegroups.com
Hi Joel,
I managed to find the solution today using the same approach. Anyways thanks for replying and showing concern. Really appreciate that :) I am new to django so these things usually take up my wole day , lol xD

Efe

unread,
Jan 22, 2020, 7:37:17 AM1/22/20
to Django users
Excelente!! Muchas gracias!!
>> To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages