Ryan Saxe
Ryan Saxe

Reputation: 17829

Django ensure blank field

I would like to be able to disable the ability to fill in a field, while having it still be created in the DB.

This column will be dependent on the rest of the rows in the table, and always will, so it is a necessary column, but the information cannot be given during creation. Here is what I have:

class FooBar(models.Model):
    some_field = models.BigIntegerField(blank=True)
    another_field = models.CharField(max_length=100)

    def save(self, *args, **kwargs):
        if not self.some_field:
            self.some_field = FooBar.objects.filter(another_field=self.another_field).count() + 1
            super(FooBar,self).save(*args,**kwargs)

this makes sense logically, you can create a FooBar instance and then once it is saved, if some_field is blank, it will assign it based on how many rows are in the table dependent on another_field. But here is the problem:

What if, when creating the instance, a value was given for some_field? That is possible and would break everything...how can that be prevented?

note: I apologize if there are any errors in the code, I have not run any of it, it is just pseudo code to display a level of dependency, thanks!

Upvotes: 1

Views: 84

Answers (2)

svvac
svvac

Reputation: 6124

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")

Upvotes: 0

sk1p
sk1p

Reputation: 6735

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.

Upvotes: 2

Related Questions