3

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

Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90

3 Answers3

3

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.

schillingt
  • 13,493
  • 2
  • 32
  • 34
  • OK, might found a solution over here: https://stackoverflow.com/q/22650758/1718174 . Still doesn't understand why is it recording and empty string if I have not defined a default value. Any idea on that? – Vini.g.fer May 21 '19 at 01:40
  • It's defaulting to an empty string. Since you have specified `null=False`, the next logical value is an empty string. It's on you as the the developer to make sure the data is valid according to your own business logic. – schillingt May 21 '19 at 01:44
  • Simply not defining a default value will not validate that the value is populated before creating the instance. You need to do that. – schillingt May 21 '19 at 01:45
1

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.

aggregate1166877
  • 2,196
  • 23
  • 38
-1

You can set default = '' to your fields

vahdet
  • 6,357
  • 9
  • 51
  • 106
Morgan
  • 1
  • 2
  • 2
    This doesn't seem to answer the OP's question — they are trying to *prevent* empty values from being accepted. – jtbandes May 21 '19 at 04:24