禁用 ModelMultipleChoiceField CheckBoxSelectMultiple Django 中的选择 [英] Disable Choice In ModelMultipleChoiceField CheckBoxSelectMultiple Django

查看:18
本文介绍了禁用 ModelMultipleChoiceField CheckBoxSelectMultiple Django 中的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,

我已经研究了几天,但似乎无法找到我要找的东西.我很清楚使用以下内容禁用 Django 表单中的字段:

I have researched this for a couple of days, and can't quite seem to find what I'm looking for. I am well aware of using the following to disable a field in a Django form:

self.fields['author'].disabled = True

以上将完全禁用一个字段.我试图显示一个带有多个选择选项的复选框,但我希望自动选择和禁用其中一个选项,以便用户无法将其更改为他们选择的选项之一.这是我一直用来显示复选框的代码,它工作正常:

The above will disable a field entirely. I am trying to display a checkbox with multiple select options, but I want one of the choices to be automatically selected and disabled so the user can not change it as one of the choices they have selected. Here is the code that I've been using to display the checkbox and it works fine:

self.fields['author'] = forms.ModelMultipleChoiceField(
                        queryset=User.objects.all(),  
                        widget=forms.CheckboxSelectMultiple(),
                        initial = user.favorite)

user.favorite 正按我的预期显示,但我想禁用它以便它仍然被选中,但用户无法更改它,但他们仍然可以在复选框中选择其他人.这可能吗?提前致谢.

The user.favorite is displaying as I would expect, but I'd like to disable it so that it's still checked, but the user can't change it, but they can still select others in the checkbox. Is this possible? Thanks in advance.

推荐答案

我创建了我的自定义小部件,并覆盖了一个方法:

I created my custom widget with one method overridden:

MY_OPTION = 0
DISABLED_OPTION = 1
ITEM_CHOICES = [(MY_OPTION, 'My Option'), (DISABLED_OPTION, 'Disabled Option')]

class CheckboxSelectMultipleWithDisabledOption(forms.CheckboxSelectMultiple):

    def create_option(self, *args, **kwargs):
        options_dict = super().create_option(*args, **kwargs)

        if options_dict['value'] == DISABLED_OPTION:
            options_dict['attrs']['disabled'] = ''

        return options_dict

然后在表格中:

class MyForm(forms.Form):

    items = forms.MultipleChoiceField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['items'].widget = CheckboxSelectMultipleWithDisabledOption()
        self.fields['items'].choices = ITEM_CHOICES

对于更复杂的情况,您可以覆盖自定义小部件的 __init__ 并在那里传递其他参数(在我的情况下,我必须传递表单的 initial 值).

For more complicated cases you can override your custom widget's __init__ and pass additional arguments there (in my case I had to pass my form's initial value).

这篇关于禁用 ModelMultipleChoiceField CheckBoxSelectMultiple Django 中的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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