正如您在下面看到的,我有带有 CharField 的模型。用户可以选择 ROLE_CHOICE 中的值之一。
问题:如何让某些值不可用但您仍然可以在选择中看到它们。
目前,我已经尝试了以下代码,但它使一些值不可见,这不是我想要的(我希望它们被禁用,而不是不可见)。
模型.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'])
最佳答案
编辑: 将 disabled 更改为内部列表中的位置 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属性!
这应该可以解决问题!
希望对您有所帮助!
关于python - 如何更改 CharField 选择列表行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743866/