带有复选框删除选项的Python Django表

时间:2018-10-04 14:28:56

标签: python django

我是Django的新手,当前正在尝试显示一个带有复选框的表,该复选框显示数据库中的记录列表,并具有一个删除按钮以使用复选框删除多个记录。

如何显示带有复选框和删除按钮的表?

感谢您的帮助!

这是与我相关的代码:

models.py

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 = ['-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

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>

1 个答案:

答案 0 :(得分:0)

我会添加到您现有的

{% for customer in customers %}

一个新的td标签,其中包括:

<td>
   <div class="checkbox">
                <input type="checkbox" name="name_check_{{customer.name}}" id="id_check{{customer.name}}"  value="1"
                    {%if customer.data == 0 %}unchecked {%else%} checked {%endif%}>     
  </div>
<td>

我用customer.data表示存储在您数据库中的值。

然后您可以编写一些js以在单击每个新复选框时执行某些操作。

<script>                                                                    
  $(document).ready(function() {
     $("#id_check_{{customer.id}}").on("click", function(){
        #do something / ajax call etc..

OR

将这些值传递回表单发布中的视图(我们为客户指定了每个复选框),然后从那里处理删除。