正如您在下面看到的,我有模型与CharField 。用户可以在 ROLE_CHOICE 中选择一个值。
问题:如何使某些值不可用,但您仍然可以在选择中看到它们。
目前,我已经尝试了以下代码,但它使一些值不可见,这不是我想要的(我希望它们被禁用,而不是不可见)。
model.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,)
forms.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'])
答案 0 :(得分:1)
编辑: 将禁用更改为内部列表中的位置0! forms.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'))
也就是说,对于需要禁用的所有字段,您需要添加标签和禁用属性!
这应该可以做到!
希望它有所帮助!