<p>正如<a href="https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot/34538169#34538169">this answer</a>中指出的,Django 1.9添加了<a href="https://docs.djangoproject.com/en/stable/ref/forms/fields/#disabled" rel="noreferrer">Field.disabled</a>属性:</p>
<blockquote>
<p>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.</p>
</blockquote>
<p>对于Django 1.8和更早版本,要禁用小部件上的条目并防止恶意的后黑客攻击,除了在表单字段上设置<code>readonly</code>属性外,还必须清除输入:</p>
<pre><code>class ItemForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
self.fields['sku'].widget.attrs['readonly'] = True
def clean_sku(self):
instance = getattr(self, 'instance', None)
if instance and instance.pk:
return instance.sku
else:
return self.cleaned_data['sku']
</code></pre>
<p>或者,用另一个指示您正在编辑的条件替换<code>if instance and instance.pk</code>。您还可以在输入字段上设置属性<code>disabled</code>,而不是<code>readonly</code>。</p>
<p><code>clean_sku</code>函数将确保<code>readonly</code>值不会被<code>POST</code>重写。</p>
<p>否则,没有内置的Django表单字段在拒绝绑定的输入数据时提供值。如果这是您所希望的,那么您应该创建一个单独的<code>ModelForm</code>来排除不可编辑的字段,并将它们打印在模板中。</p>