0

I am creating a django DB model and I want one the fields to be readonly. When creating a new object I want to set it, but later if someone tries to update the object, it should raise an error. How do I achieve that?

I tried the following but I was still able to update the objects.

from django.db import models as django_db_models


class BalanceHoldAmounts(django_db_models.Model):
    read_only_field = django_db_models.DecimalField(editable=False)

Thank you

Epic
  • 572
  • 2
  • 18

1 Answers1

0

You can override it in the "save" method of the model and raise a Validation Error if someone tries to update that field.

def save(self, *args, **kwargs):
    if self.pk:
        previous_value = BalanceHoldAmounts.objects.get(pk=self.pk)
        if previous_value.read_only_field != self.read_only_field:
            raise ValidationError("The read_only_field can not be changed")    
    super().save(*args, **kwargs)
R D
  • 1
  • 3