在Django有没有办法把选择显示为复选框? [英] In Django is there a way to display choices as checkboxes?

查看:936
本文介绍了在Django有没有办法把选择显示为复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在管理界面和新格式中,有能力定义选择的辉煌助手。您可以使用这样的代码:

  APPROVAL_CHOICES =(
('是','是'),
('no','No'),
('取消','已取消'),


client_approved = models.CharField(choices = APPROVAL_CHOICES)

在您的表单中创建一个下拉框,并强制用户选择其中一个选项。 p>

我只是想知道是否有一种方法来定义一组可以使用复选框选择多个选项的选项? (也可以说可以说用户可以选择最大数量)这似乎是一个可能实现的功能,只是我似乎无法在文档中找到它。

解决方案

根据表单库,您可以使用 MultipleChoiceField 字段与 CheckboxSelectMultiple 小部件做到这一点。您可以通过编写字段的验证方法来验证所选择的数量:

  class MyForm(forms.Form) :
my_field = forms.MultipleChoiceField(choices = SOME_CHOICES,widget = forms.CheckboxSelectMultiple())

def clean_my_field(self):
if len(self.cleaned_data ['my_field '])> 3:
raise forms.ValidationError('Select no more than 3')
return self.cleaned_data ['my_field']

要在管理应用程序中获取此信息,您需要自定义一个ModelForm和覆盖适当的ModelAdmin中使用的表单


In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:

APPROVAL_CHOICES = (
    ('yes', 'Yes'),
    ('no', 'No'),
    ('cancelled', 'Cancelled'),
)

client_approved = models.CharField(choices=APPROVAL_CHOICES)

to create a drop down box in your form and force the user to choose one of those options.

I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.

解决方案

In terms of the forms library, you would use the MultipleChoiceField field with a CheckboxSelectMultiple widget to do that. You could validate the number of choices which were made by writing a validation method for the field:

class MyForm(forms.Form):
    my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())

    def clean_my_field(self):
        if len(self.cleaned_data['my_field']) > 3:
            raise forms.ValidationError('Select no more than 3.')
        return self.cleaned_data['my_field']

To get this in the admin application, you'd need to customise a ModelForm and override the form used in the appropriate ModelAdmin.

这篇关于在Django有没有办法把选择显示为复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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