简体   繁体   中英

Django CharField accepting empty values when it shouldn't

I have the following model:

class ClientDebt(models.Model):
    client_id = models.CharField(max_length=255)
    ...

I was expecting this model to prevent records without a client_id, but I quite don't understand why I can create a ClientDebt without a client_id using a django shell ( python manage.py shell_plus ).

Changing it to CharField(max_length=255, null=False, blank=False) and trying to create+execute new migrations also didn't work, as Django did not detected any changes. There is no default value from what I could see in previous migrations, but it seems to be recording "" (empty string) in the field.

Can anybody tell me what is going on? Why is my model accepting null/blank values? Can this be a bug in Django? I'm using Django version 2.2.1

blank is only used with form validation. If you are having records created with empty values you'll need to write some custom checks to prevent that.

Have a look at this answer :

class ClientDebt(models.Model):
    client_id = models.CharField(max_length=255, blank=False, default=None)
    ...
  • blank will prevent an empty string to be provided in your model
  • default=None will set name to None when using something like group = Group() , thus raising an exception when calling save

Alternatively, you may want to have a look at MinLengthValidator .

您可以在字段中设置default = ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM