#36286 closed Bug (invalid)
if I specify `null=False, blank=False` in a `models.TextField`, django should not generate a blank string for me
| Reported by: | bwo | Owned by: | |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
Suppose I have an existing model M with integer-valued fields a and b and somewhere in my test code I do this: M.objects.create(a=1, b=2).
Now I create add a new non-nullable string-valued field by altering M's definition like so:
class Choices(models.TextChoices):
one = ("one", "one")
two = ("two", "two")
class M(models.Model):
# existing fields omitted
c = models.TextField(null=False, choices=Choices.choices)
I add some code that switches on the value of c, knowing that it will certainly be either "one" or "two" (even though django actually does no validation here…). I run tests, confident in the knowledge that either Django or the database will complain at every site that doesn't set a value for c.
In fact, this doesn't happen. The value of c, if not provided, generated and set to ''. This behavior by itself strikes me as a bug: if I wanted it to be ok to not provide a value for c, I wouldn't have made it non-nullable. But fine, let's add a blank=False (eve though this parameter is apparently related to forms) to the definition and try again.
It's still ''!
Change History (2)
comment:1 by , 7 months ago
| Resolution: | → wontfix |
|---|---|
| Status: | new → closed |
comment:2 by , 7 months ago
| Component: | Uncategorized → Database layer (models, ORM) |
|---|---|
| Resolution: | wontfix → invalid |
| Type: | Uncategorized → Bug |
| Version: | 5.1 → dev |
Thank you Clifford for the triage! I will just adjust the resolution, since for tickets that are a user support request we usually close them as invalid. We usually use wontfix for New Feature requests.
See #35671 and https://forum.djangoproject.com/t/get-or-create-and-create-with-unspecified-non-nullable-fields/33755.
Empty strings do not violate
null=Falseand they are the default empty value for string-based fields. If you don't want them as defaults, consider settingdefault=None. `blank=False will only disallow them in forms, not in Python code.