开发者

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

开发者 https://www.devze.com 2023-03-25 16:18 出处:网络
I have a simple model which looks l开发者_开发百科ike this: class Group(models.Model): name = models.CharField(max_length = 100, blank=False)

I have a simple model which looks l开发者_开发百科ike 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?


another option that doesn't require you to manually call clean is to use this:

name = models.CharField(max_length=100, blank=False, default=None)
  • blank will prevent an empty string to be provided in the admin or using a form or serializer (most cases). However as pointed out in the comments, this unfortunately does not prevent things like model.name = "" (manually setting blank string)
  • default=None will set name to None when using something like group = Group(), thus raising an exception when calling save


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.


Or you can simply use MinLengthValidator with a 1-char minimum:

from django.core.validators import MinLengthValidator

class Company(BaseModel):
    """Company"""

    name = models.CharField(max_length=255,
                            validators=[MinLengthValidator(1)])


I spent a long time looking for the best solution for this simple (and old) problem, And as of Django 2.2, there is actually a really simple answer, so I'll write it here in case someone still encounters the same problem:

Since Django 2.2, we can define CheckConstraints, so it's easy to define a non-empty string constraint:

from django.db import models

class Article(models.Model):
   title = models.CharField(max_length=32)

    class Meta:
        constraints = [
            models.CheckConstraint(check=~models.Q(title=""), name="non_empty_title")
        ]


Django’s validation system assumes that all fields are required,unless you mention that its ok to leave it blank..

Have you registered the class in Admin ? does it show errors when you leave it blank ??

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

0

精彩评论

暂无评论...
验证码 换一张
取 消