eatonphil
eatonphil

Reputation: 13682

optional fields in django models

I have the following model in django.

class Link(models.Model):
    name = models.CharField(max_length=100)
    url = models.CharField(max_length=100)
    tag = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

I need the url field to be optional. How do I do this?

Upvotes: 51

Views: 57985

Answers (2)

Adam
Adam

Reputation: 1518

Setting null=True for CharField is not recommended, as you can see from django docs:

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

So I would recommend this configuration:

name = models.CharField(max_length=100, blank=True, default='')

Upvotes: 50

mipadi
mipadi

Reputation: 410662

Add the attribute blank=True. Optionally, you can also make the field NULLable with null=True.

Upvotes: 81

Related Questions