In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

后端 未结 26 1010
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:09

In a Django form, how do I make a field read-only (or disabled)?

When the form is being used to create a new entry, all fields should be enabled - but when the recor

26条回答
  •  故里飘歌
    2020-11-22 04:13

    How I do it with Django 1.11 :

    class ItemForm(ModelForm):
        disabled_fields = ('added_by',)
    
        class Meta:
            model = Item
            fields = '__all__'
    
        def __init__(self, *args, **kwargs):
            super(ItemForm, self).__init__(*args, **kwargs)
            for field in self.disabled_fields:
                self.fields[field].disabled = True
    

提交回复
热议问题