2017-03-12 8 views
3

以下に示すように、私はCharFieldのモデルを持っています。ユーザーはROLE_CHOICEの中から1つの値を選択できます。CharFieldの選択肢の動作を変更する方法

質問:一部の値を使用できないようにするにはどうすればよいですか。選択した値は引き続き表示できます。

現在、私は以下のコードを試しましたが、一部の値が見えなくなりました。これは私が望むものではありません。

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']) 

enter image description here

答えて

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) 

は、無効にする必要があり、すべてのフィールドのために、あなたはラベルとdisabled属性を追加する必要がありますされ

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

を与えます!

それはすごいです!

希望すると助かります!

+0

こんにちは、私はあなたのコードを試しましたが、残念ながらそれは仕事をしませんでした。それでも選択可能です。私は私のポストに画像を追加しました。あなたはそれがどのように見えるかを見ることができます、plsを確認してください。あなたはなにか考えはありますか? –

+0

私は編集内容を追加しました!あなたはまだエラーがある場合私に教えて! –

+0

私はそれをテストしました。それでも選択可能なユーザーは開発者を選択できますが、フォームの検証作業は可能です。実際、それはあなたが必要とするものではありません。多分私はテンプレートではなく、フォームで無効になっている選択が必要だと思いますか?もう一度plsを見てください。私は絵を編集する。 –

関連する問題