具有多个选择的下拉表单

具有多个选择的下拉表单

本文介绍了Django-具有多个选择的下拉表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建Django 下拉列表 forms.Form 字段的指南,在其中可以选择多个选择。我需要在表单的办公室字段中选择多个位置。



提交后,表单需要返回所选办公室的列表(例如 [ New York, Los Angeles] [奥斯丁] )。返回 tuple 也可以。






我能做到的最好现在要做的是为<$ c $构建一个






但是,我希望此字段为下拉菜单,以减少页面上的空间。



我发现了这个,但是( 1)少数人提到它似乎已经过时(我无法确认),并且(2)我首先要检查一个内置的django表单/窗口小部件安装程序是否可以完成此任务,然后再使用自定义代码。

解决方案

Dropdown框不支持HTML中的多选;浏览器将始终将其呈现为图像显示的平面框。



您可能想使用某种JS小部件-是一种流行的方法。有几个Django项目-,-旨在简化将其集成到表单中的过程;我对它们中的任何一个都没有经验。



(是的,就像Djangosnippets上的许多东西一样,该代码段已经过时; newforms重命名为表单(甚至在Django 1.0版之前)。


I need guidance building a django dropdown forms.Form field in which I can select multiple choices. I need to select multiple locations on the office field of the form.

When submitted, the form needs to return a list of the chosen offices (e.g. ["New York", "Los Angeles"] or ["Austin"]). Returning a tuple is also acceptable.


The best I can do right now is build a multipleChoiceField for office with the following:

from django import forms

class my_Form(forms.Form):

    OPTIONS = [
        ("0", "*ALL"),
        ("1", "New York"),
        ("2", "Los Angeles"),
        ]

    office = forms.MultipleChoiceField(
            choices=OPTIONS,
            initial='0',
            widget=forms.SelectMultiple(),
            required=True,
            label='Office',
        )

resulting in this form field layout:


However, I would like this field to be a dropdown, to take up less space on the page.

I found this djangosnippet but (1) a few people have mentioned it appears out of date (I can't confirm), and (2) I first want to check if a built-in django form/widget setup can fulfill this task before using custom code.

解决方案

"Dropdown" boxes don't support multiple selection in HTML; browsers will always render it as a flat box as your image shows.

You probably want to use some kind of JS widget - Select2 is a popular one. There are a couple of Django projects - django-select2, django-easy-select - that aim to make it simple to integrate that into your form; I have no experience with either of them.

(And yes, that snippet - like many things on Djangosnippets - is massively out of date; "newforms" was renamed to "forms" even before version 1.0 of Django.)

这篇关于Django-具有多个选择的下拉表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:08