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

查看:69
本文介绍了在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天全站免登陆