Sazzadur Rahman
Sazzadur Rahman

Reputation: 2940

Django is putting empty string by default while expecting it to be null in DB column

I am using postgresql version 10.6 with my Django 2.1 application. The problem is that when I am using null=True in my model field it is translating to empty string ('') in database column as default where I am trying default it as null.

In my following code sample image column should be null:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='profile_pics', null=True, blank=True) 

And I am calling this class from a signal like this:

@receiver(post_save, sender=User)
def create_profile(sender, **kwargs):
    if kwargs.get('created') is True:
        Profile.objects.create(user=kwargs.get('instance'))

In this snapshot you can see that image column is inserting as empty string instead of null

enter image description here

I have also tried to use default value for my model field as:

image = models.ImageField(default=None, upload_to='profile_pics', null=True, blank=True)

but it doesn't work either.

Upvotes: 0

Views: 2241

Answers (2)

Kaan Karaca
Kaan Karaca

Reputation: 190

Null: It is database-related. Defines if a given database column will accept null values or not.

Blank: It is validation-related. It will be used during forms validation when calling form.is_valid().

The default values of null and blank are False.

You should remove blank=True

Upvotes: -1

Exprator
Exprator

Reputation: 27523

image = models.ImageField(upload_to='profile_pics', null=True) 

remove the blank=True

Upvotes: 0

Related Questions