社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  问与答

Django怎么通过checkbox多选删除数据库数据?

HelloSam • 8 年前 • 7258 次点击  

一下是我模板里checkbox多选删除的 代码:

{% for report_table_context in report_table.values_list %}
        <tr>
            {% for report_table_context_data in report_table_context %}
                {% if forloop.counter != 1 %}
                    <td> {{ report_table_context_data  }}</td>
                {% else %}
                    <td><input type="checkbox"  name="ids" value=report_table_context_data /></td>
                {% endif %}
            {% endfor %}
        </tr>
{% endfor %}

其中 ,当forloop == 1时,report_table_context_data的值是id。所以,该table的第一列 是checkbox。

一下是我view里的代码:

if request.method == 'POST':
    id_list = request.POST.getlist('ids')
    for id in id_list.getvalue:
        RepairReport.objects.filter(report_table_id = id).delete()

请问应该怎么写这些代码?我这样写是实现不了的。而且我不知道id_list有没有getvalue()这个方法……求指教?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/1214
 
7258 次点击  
文章 [ 22 ]  |  最新文章 8 年前
HelloSam
Reply   •   1 楼
HelloSam    8 年前

@MCC 请问一下这个 视图函数

def  addreport(request):
pre_report_entering_form = ReportEnteringForm()
if request.method == 'POST':
    pre_report_entering_form = ReportEnteringForm( request.POST )
    # 这里是增添数据部分
    if pre_report_entering_form.is_valid():
        pre_report_entering_form.clean()
        pre_report_entering_form.save( commit = True )
        # pre_report_entering_form在渲染前 清空
        pre_report_entering_form = ReportEnteringForm()
return render_to_response('addreport.html', RequestContext(request,
                                                           {'report_entering_form':pre_report_entering_form}
                                                           )
                          )

怎么修改成为继承TemplateView的类视图? 我写了这样的,但是运行不了:

class AddReportView(TemplateView):
"""
把表单填写数据存入数据库
"""
template_name = 'reportTemplate.html'

def __init__(self):
    report_entering_form = ReportEnteringForm()

def post(self, request):
    report_entering_form = ReportEnteringForm( request.POST )
    # 这里是增添数据部分
    if report_entering_form.is_valid():
        report_entering_form.clean()
        report_entering_form.save( commit = True )
        # pre_report_entering_form在渲染前 清空
        report_entering_form = ReportEnteringForm()

def get_context_data(self, **kwargs):
    context = super(AddReportView, self).get_context_data(**kwargs)
    context['report_entering_form_context'] = report_entering_form
    return context
MCC
Reply   •   2 楼
MCC    8 年前

@HelloSam 我没在模板里做过类似的功能

不太明白check的权限具体指什么

https://docs.djangoproject.com/en/1.8/topics/auth/default/#default-permissions

可以尝试一下

HelloSam
Reply   •   3 楼
HelloSam    8 年前

@MCC 你好,我现在遇到一个问题。有一个用户叫A,他没有任何权限,但是他所在的组有一个check权限。我在模板里面用了 这样的语句:

   {% if perms.check %}
        </a> <a href="check"> <span>checkspan>
   {% endif %}

结果是没有反应的。原因可能是perms只对 用户本身设置的权限进行判断,无法对 用户所在组 的权限进行判断。这样做就很麻烦了。我希望是:用户不需要设置权限,只需要把他加进相应的组,然后判断组的权限就OK了。那么在模板语言里,我应该怎么做?

HelloSam
Reply   •   4 楼
HelloSam    8 年前

@MCC 我现在有一个问题:一个界面需要同时把父模板和子模板都显示出来。父模板和子模板是用两个不同的 视图函数 去渲染的。我想知道怎么能够同时调用 两个视图函数,对父模板和子模板进行渲染,显示在这个这界面中。

HelloSam
Reply   •   5 楼
HelloSam    8 年前

@MCC 好的 ~~~谢谢分享~按照你这样做,我的 多选删除成功实现了 ~

MCC
Reply   •   6 楼
MCC    8 年前

@HelloSam 我只是举例子用,页面上选中的is_checked设置为True 没选中的是False,如果你的实现中不需要就可以干掉它

HelloSam
Reply   •   7 楼
HelloSam    8 年前

@MCC 按照你的做法,is_checked这个属性一定要包含在模型里面 吗?

HelloSam
Reply   •   8 楼
HelloSam    8 年前

@shen_gan 谢谢分享~~~

MCC
Reply   •   9 楼
MCC    8 年前

╮(╯▽╰)╭这论坛不让编辑不舒服,细节自己调试了

MCC
Reply   •   10 楼
MCC    8 年前

啊 遍历太慢,删除不用那么麻烦

int_id_list = [int(id) for id in id_list]  # convert to int
for id in int_id_list :
    try:
        Item.object.get(id=id).delete()
    except Item.DoesNotExist:
        pass
MCC
Reply   •   11 楼
MCC    8 年前

我例子上没删除数据,因为加起来麻烦,要删除就

for item in items:
    if  item.id in int_id_list:
        item.delete()
MCC
Reply   •   12 楼
MCC    8 年前

临时写了个例子,没用js和ajax

models.py

from django.db import models


class Item(models.Model):
    data = models.CharField(max_length=255)
    is_checked = models.BooleanField(default=False)

views.py

from django.shortcuts import render_to_response
from django.shortcuts import RequestContext
from models import Item


def example(request):
    items = Item.objects.all()
    if request.method == 'POST':
        # if nothing checked, 'ids' will not in POST, it will return []
        id_list = request.POST.getlist('ids')
        int_id_list = [int(id) for id in id_list]  # convert to int
        for item in items:
            item.is_checked = item.id in int_id_list
            item.save()
    return render_to_response(
        "example/example.html",
        {
            'items': items,
        },
        context_instance=RequestContext(request),
    )

templates/example/example.html

<h1>Example</h1>
<form action method="post">
    {% csrf_token %}
    {% for item in items %}
    <input type="checkbox" name="ids" value="{{ item.id }}" {% if item.is_checked %}checked{% endif %}/>{{ item.data }}<br>
    {% endfor %}
    <input type="submit" />
    <input type="reset" /></p>
</form>
shen_gan
Reply   •   13 楼
shen_gan    8 年前

@HelloSam 之前做过,用的是 javascript 实现。

  1. 添加一个hidden input

    <input type="hidden" id="id_ids" name="ids" value="">
    
  2. 遍历所有的 checkbox,选出勾选的组成字符串(比如,"value1, value2, value3")。

  3. 然后将此字符串赋值给上面的那个hidden input

  4. 在django视图中就可以通过 request.POST.get('ids') 来获取ids,然后就是 ids = ids.split(',')

  5. 接下来就是删除了~~

MCC
Reply   •   14 楼
MCC    8 年前

@HelloSam ajax就要JsonResponse

你这需求不用ajax也可以啊,问题要你自己调试啊。我是不知道你现在report_table.values_list里面啥样的。

1 在网页上获取源看表单里面到底渲染成啥样了,基本知道template里面如果有错错在哪儿了,顶楼里面至少第七行的value=report_table_context_data ,report_table_context_data 周围要加引号双括号

2 自己在views里面用断点或者直接加print

if request.method == 'POST':
    id_list = request.POST.getlist('ids')
    print  id_list

(看上去比较傻X)但是至少可以看id_list到底有没有拿到,就知道问题在哪儿了

HelloSam
Reply   •   15 楼
HelloSam    8 年前

听说要通过javascript和ajax来实现~但不知道怎么实现

HelloSam
Reply   •   16 楼
HelloSam    8 年前

问题还没得到解决,请各位大神帮帮忙~~~

MCC
Reply   •   17 楼
MCC    8 年前

" value="{{report_table_context_data.id}}" 要不要.id自己调试

HelloSam
Reply   •   18 楼
HelloSam    8 年前

@MCC 这样改后,没有成功~会不会是模板那里的 代码错了?应该怎么给checkbox的value赋值???

HelloSam
Reply   •   19 楼
HelloSam    8 年前

@MCC 谢谢分享~~~

MCC
Reply   •   20 楼
MCC    8 年前

以前我一片代码是这样的

def today(request):
    people_name = ['Jill', 'Jason', 'CCC', 'Zoe']
    count = 2
    if request.method == 'POST':
        if 'people' in request.POST:
            people_name = request.POST.getlist('people')
            print people_name
        if 'count' in request.POST:
            count = int(request.POST.get('count'))
    people = get_luck(people_name, count)
    return render_to_response(
        "today/today.html",
        {
            'people': people,
            'count': count,
        },
        context_instance=RequestContext(request),
    )