如何更改CharField选项列表行为

2024-04-26 07:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

正如你在下面看到的,我有一个带有CharField的模型。用户可以在角色选择中选择一个值。你知道吗

问题:如何使某些值不可用,但您仍然可以在选择中看到它们。你知道吗

目前,我已经尝试了以下代码,但它使一些值不可见,这不是我想要的(我希望他们禁用,而不是不可见)。你知道吗

型号.py

ROLE_CHOICES = (
        ('manager', 'Manager'),
        ('developer', 'Developer'),
        ('business_analyst', 'Business analyst'),
        ('system_analysts', 'System analysts'),
)


class Membership (models.Model):
    ***OTHER FIELDS***
    role = models.CharField(max_length=20, choices=ROLE_CHOICES,)

表单.py

class MembershipForm(forms.ModelForm):
    class Meta:
        model = Membership
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MembershipForm, self).__init__(*args, **kwargs)
        self.fields['role'].choices = tuple(choice for choice in ROLE_CHOICES if choice[0] not in ['developer'])

enter image description here


Tags: pyselfdevelopermodelsclassrolemembershipchoices
1条回答
网友
1楼 · 发布于 2024-04-26 07:17:37

编辑: 已将“禁用”更改为内部列表中的位置0! 表单.py你知道吗

class MembershipForm(forms.ModelForm):
    class Meta:
        model = Membership
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MembershipForm, self).__init__(*args, **kwargs)
        self.fields['role'].choices = tuple(choice if choice[0] not in ['developer'] else ({"label":choice[1],"disabled":True},choice[0]) for choice in ROLE_CHOICES )

在这里

tuple(choice if choice[0] not in ['developer'] else ({"label":choice[1],"disabled":True},choice[0]) for choice in ROLE_CHOICES )

将给予

(('manager', 'Manager'), ( {'disabled': True, 'label': 'developer'}, Developer), ('business_analyst', 'Business analyst'), ('system_analysts', 'System analysts'))

也就是说,对于所有需要禁用的字段,您需要添加label和disabled属性!你知道吗

这就应该成功了!你知道吗

希望有帮助!你知道吗

相关问题 更多 >