Python Django 表单中的只读字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41271979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read-Only Field in Django Form
提问by Foobar
How do I set a field to read-only in a Django form? I know how to disable a field but that's not what I'm looking for. Any help would be appreciated.
如何在 Django 表单中将字段设置为只读?我知道如何禁用一个字段,但这不是我要找的。任何帮助,将不胜感激。
回答by nael
You can use the optional attrs
parameter when defining the Field
. To wit:
您可以attrs
在定义Field
. 以机智:
somefield = forms.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
回答by mtt2p
In django 1.9in a Field.disabled attribute available : https://docs.djangoproject.com/en/1.9/ref/forms/fields/#disabled
在django 1.9中可用的 Field.disabled 属性:https://docs.djangoproject.com/en/1.9/ref/forms/fields/#disabled
The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.
disabled 布尔参数设置为 True 时,会使用 disabled HTML 属性禁用表单字段,以便用户无法对其进行编辑。即使用户篡改了提交给服务器的字段值,它也会被忽略,取而代之的是表单初始数据中的值。
otherwise
除此以外
use the widget 'readonly' attribute
使用小部件“只读”属性
class PatientForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PatientForm, self).__init__(*args, **kwargs)
self.fields['field'].widget.attrs['readonly'] = True
class Meta:
model = Patient
回答by surfer190
In Django 1.9+
:
在Django 1.9+
:
somefield = forms.CharField(disabled=True)