具有未知数量的复选框字段和多个操作的 Django 表单 [英] Django form with unknown number of checkbox fields and multiple actions

查看:21
本文介绍了具有未知数量的复选框字段和多个操作的 Django 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关看起来像 Gmail 收件箱并有多项操作的表单的帮助.有一个项目列表,我想用表单将它包装起来,就像每个项目在行的前面都有复选框一样.因此,当用户选择几个项目时,他可以点击两个按钮执行不同的操作,例如删除和标记为已读.

I need help with form which looks like a Gmail inbox and have multiple actions. There is a list of items and I want to wrap it with form, on the way that every item have checkbox in the front of the line. So when user select few items he is able to click on two buttons with different actions for example delete and mark read.

<form action="">
    {% for item in object_list %}
    <input type="checkbox" id="item.id">
    {{ item.name }}
    {% endfor %}
    <button type="submit" name="delete">Delete</button>
    <button type="submit" name="mark_read">Mark read</button>
</form>

如果在 request.POST 中使用 if 'delete',我可以找到用户点击哪个提交按钮,但我无法引用任何表单,因为 Django 表单无法定义为未知数量的字段,因为我思考.那么如何处理视图中的选定项目?

I can find which submit button is user click on if use if 'delete' in request.POST but I cant refer to any form because Django form cant be defined with unknown number of fields as I think. So how can I process selected items in view?

if request.method == 'POST':
    form = UnknownForm(request.POST):
    if 'delete' in request.POST:
        'delete selected items'
    if 'mark_read' in erquest.POST:
        'mark selected items as read'
    return HttpResponseRedirect('')

推荐答案

多个同名复选框都是同一个字段.

Multiple checkboxes with the same name are all the same field.

<input type="checkbox" value="{{item.id}}" name="choices">
<input type="checkbox" value="{{item.id}}" name="choices">
<input type="checkbox" value="{{item.id}}" name="choices">

您可以使用单个 django 表单字段来收集和聚合它们.

you can collect and aggregate them with a single django form field.

class UnknownForm(forms.Form):
    choices = forms.MultipleChoiceField(
        choices = LIST_OF_VALID_CHOICES, # this is optional
        widget  = forms.CheckboxSelectMultiple,
    )

具体来说,您可以使用 ModelMultipleChoiceField.

Specifically, you can use a ModelMultipleChoiceField.

class UnknownForm(forms.Form):
    choices = forms.ModelMultipleChoiceField(
        queryset = queryset_of_valid_choices, # not optional, use .all() if unsure
        widget  = forms.CheckboxSelectMultiple,
    )

if request.method == 'POST':
    form = UnknownForm(request.POST):
    if 'delete' in request.POST:
        for item in form.cleaned_data['choices']:
            item.delete()
    if 'mark_read' in request.POST:
        for item in form.cleaned_data['choices']:
            item.read = True; item.save()

这篇关于具有未知数量的复选框字段和多个操作的 Django 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆