In a django form, How to make a field readonly (or disabled) so that it cannot be edited?
When the form is being used for a new record entry, all fields are enabled, but when the record is in update mode some fields need to be readonly.
For example, in the Item model, for a new record entry, all fields are editable, but while updating the record, is there a way to disable 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
can class ItemForm be used reused? What changes would be required in 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()