Mitch Downey
Mitch Downey

Reputation: 917

How to allow a form to submit, but prevent blank fields from being saved using Django Admin 3.x?

I am using Django Admin, and have a model like this:

class Item(models.Model):

    id = models.CharField(max_length=14, primary_key=True)
    otherId = models.CharField(max_length=2084, blank=True)

I want id to be required and unique, and I want otherId to be optional on the Admin form, but if otherId is provided, it has to be unique.

The problem I am running into is, whenever I create an instance of Item using the Admin form and I do not provide an otherId, Django tries to save the otherId field as a blank value, but this means the second time I try to save an instance with a blank otherId value it violates the column's unique constraint and fails.

I need Django to check if the otherId field is falsey before saving, and if it is falsey, do not save that empty value along with the model. Is this possible?

Upvotes: 0

Views: 1619

Answers (3)

Shakthi
Shakthi

Reputation: 31

For disabling submission of blank field you must make the null and blank property False. Check the code. Also note that the id field is automatically added in django so you need not mention that.

class Item(models.Model):
    otherId = models.CharField(max_length=2084, blank=False, null=False)

Upvotes: 0

Simon Peter Ojok
Simon Peter Ojok

Reputation: 166

I failed to understand the question very well but i think you need to override the save method of the django model and provide custom logic you stated above.

class Item(models.Model):
    id = models.CharField(max_length=14, primary_key=True)
    otherId = models.CharField(max_length=2084, blank=True)
    def save(self, *args, **kwargs): 
        
        # handle you logic here 
        # check if self.id is empty string and do something about it
        super(Item, self).save(*args, **kwargs)

For every model django also auto create a field id for primary key which is auto generated and incremented.

Upvotes: 0

technobic
technobic

Reputation: 36

You should add unique=True to otherId field.

otherid = models.CharField(max_length=2084, blank=True, null=True, unique=True)

Django ignore unique or not if otherId is blank.

Upvotes: 1

Related Questions