问题描述
在Django表单中,如何使字段为只读(或禁用)?
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 record is in update mode some fields need to be read-only.
例如,创建新的项目
模型,所有字段必须是可编辑的,但是在更新记录时,是否有一种方法来禁用 sku
字段,使其可见,但是不能编辑?
For example, when creating a new Item
model, all fields must be editable, but while updating the record, is there a way to disable the sku
field so that it is visible, but cannot be edited?
class Item(models.Model):
sku = models.CharField(max_length=50)
description = models.CharField(max_length=200)
added_by = models.ForeignKey(User)
class ItemForm(ModelForm):
class Meta:
model = Item
exclude = ('added_by')
def new_item_view(request):
if request.method == 'POST':
form = ItemForm(request.POST)
# Validate and save
else:
form = ItemForm()
# Render the view
可以将类 ItemForm
被重用?在 ItemForm
或项目
模型类中需要做哪些更改?我需要写另一个类, ItemUpdateForm
,用于更新项目?
Can class ItemForm
be reused? What changes would be required in the ItemForm
or Item
model class? Would I need to write another class, "ItemUpdateForm
", for updating the item?
def update_item_view(request):
if request.method == 'POST':
form = ItemUpdateForm(request.POST)
# Validate and save
else:
form = ItemUpdateForm()
推荐答案
在,Django 1.9添加了属性:
As pointed out in this answer, Django 1.9 added the Field.disabled attribute:
使用Django 1.8及更早版本,为了禁用窗口小部件上的条目,并防止恶意的POST黑客,您必须擦除输入,而不必在表单域上设置 readonly
属性: / p>
With Django 1.8 and earlier, to disable entry on the widget and prevent malicious POST hacks you must scrub the input in addition to setting the readonly
attribute on the form field:
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']
或者,如果instance和instance.pk 替换,另一个条件表示您正在编辑。您也可以在输入字段中设置
属性
,而不是 readonly
。
Or, replace
if instance and instance.pk
with another condition indicating you're editing. You could also set the attribute disabled
on the input field, instead of readonly
.
clean_sku
函数将确保 readonly
值不会被覆盖 POST
。
The
clean_sku
function will ensure that the readonly
value won't be overridden by a POST
.
否则,没有内置的Django表单域,它会在拒绝绑定的输入数据时呈现一个值。如果这是你想要的,你应该创建一个单独的
ModelForm
,排除不可编辑的字段,只需将它们打印在模板中。
Otherwise, there is no built-in Django form field which will render a value while rejecting bound input data. If this is what you desire, you should instead create a separate
ModelForm
that excludes the uneditable field(s), and just print them inside your template.
这篇关于在Django表单中,如何使一个字段只读(或禁用),以便无法编辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!