python - 如何更改 CharField 选择列表行为

标签 python django python-3.x django-forms django-1.9

正如您在下面看到的,我有带有 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'])

enter image description here

最佳答案

编辑: 将 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/

相关文章:

python - 如何从数据框中获取当前值来构建列表?

django - 运行时警告 : DateTimeField received a naive datetime

python - 将文件上传到 Google Cloud 并出现 Python 3 问题

python - 具有距离条件的最近邻加入

python - 在 python 中加载模块范围的配置

python - 打开 2 个文件并将它们分配给 Python 3 中的 2 个集合

python-3.x - 如何在 Django 中进行计算外键对象的查询?

python - 您的数据库没有 South 数据库模块 'south.db.postgresql_psycopg2'

python-3.x - 将 ThreadPoolExecutor 与一名工作人员一起使用是个好主意吗?

python - 解析 Python 中的语法错误时出现意外的 EOF