user3033194
user3033194

Reputation: 1831

Provide default value for optional field in Django model

I have written a Python model as given below:

from django.db import models

class Product(models.Model):


        title = models.CharField(max_length=255, unique=True)
        description = models.TextField(blank=True)
        image_url = models.URLField(blank=True)
        quantity = models.PositiveIntegerField(default=0)

        def sell(self):

                self.quantity = self.quantity - 1
                self.save()
                return self.quantity

When I am trying to create the schema using migrate, I get the following message:

You are trying to add a non-nullable field 'description' to product without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option: 

My question is, if I am setting 'blank=True' for 'description', is it necessary to specify a default value for the field? Or am I missing something else?

Upvotes: 3

Views: 5511

Answers (3)

You need to use default="".

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600049

blank=True is not the same as null=True, as the documentation explains. When a text field is blank, it still needs some kind of value: but that value can be the empty string.

So, just select option 1, and enter '' as the default value.

Upvotes: 3

wolendranh
wolendranh

Reputation: 4292

There is a ticket created for this behavior for Django 1.7. Take a look here

Upvotes: 2

Related Questions