[Answered ]-Django ensure blank field

2👍

Set editable=False on the field. This will remove it from any ModelForms and from the admin. It won’t prevent you from setting the value elsewhere in the code, though.

👤sk1p

0👍

You can override your model’s validation function to add custom code.

class YourModel(models.Model):
    ...
    # You're trying to force a single field to be blank, so you need to
    # override clean_fields().
    # If several fields were required to validate, clean() would be more
    # appropriate
    def clean_fields(self, exclude=None):
        super(models.Model, self).clean_fields(exclude)

        # Check if the field should be ignored (for consistency)
        if "your_field_that_should_be_blank" not in exclude:
            # Validate the data. I'm assuming the field holds strings
            if self.your_field_that_should_be_blank != "":
                # Raise a ValidationError if invalid
                raise ValidationError("That field should be blank")
👤svvac

Leave a comment