Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

How can you create a non-empty CharField in Django?

I have a simple model which looks like this:

class Group(models.Model):
    name = models.CharField(max_length = 100, blank=False)

I would expect this to throw an integrity error, but it does not:

group = Group() # name is an empty string here
group.save()

How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?

question from:https://stackoverflow.com/questions/6940499/how-can-you-create-a-non-empty-charfield-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Django docs in this case, your name will be stored as an empty string, because the null field option is False by default. if you want to define a custom default value, use the default field option.

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

On this page, you can see that the blank is not database-related.

Update:

You should override the clean function of your model, to have custom validation, so your model def will be:

class Group(models.Model):
  name = models.CharField(max_length=100, blank=False)
  def clean(self):
    from django.core.exceptions import ValidationError
    if self.name == '':
        raise ValidationError('Empty error message')

Or you can replace ValidationError to something else. Then before you call group.save() call group.full_clean() which will call clean()

Other validation related things are here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...