Opened 10 years ago
Closed 10 years ago
#24818 closed Bug (fixed)
models.CharField shouldn't accept a string as max_length
| Reported by: | Santiago L | Owned by: | nobody | 
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 1.8 | 
| Severity: | Normal | Keywords: | |
| Cc: | Santiago L | Triage Stage: | Accepted | 
| Has patch: | yes | Needs documentation: | no | 
| Needs tests: | no | Patch needs improvement: | no | 
| Easy pickings: | no | UI/UX: | no | 
Description
In models.CharField you can define max_length as string and the system check framework doesn't complain (related mailing list thread):
from django.db import models
class Foo(models.Model):
    bar = models.CharField(max_length='16')
>>> # following code raises an Exception
>>> obj = Foo(bar='lorem ipsum')
>>> obj.clean_fields()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 1167, in clean_fields
    setattr(self, f.attname, f.clean(raw_value, self))
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 589, in clean
    self.run_validators(value)
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py", line 541, in run_validators
    v(value)
  File "/usr/local/lib/python3.4/dist-packages/django/core/validators.py", line 280, in __call__
    if self.compare(cleaned, self.limit_value):
  File "/usr/local/lib/python3.4/dist-packages/django/core/validators.py", line 319, in <lambda>
    compare = lambda self, a, b: a > b
TypeError: unorderable types: int() > str()
      Change History (8)
comment:1 by , 10 years ago
comment:3 by , 10 years ago
| Summary: | models.CharField shouldn't accept a string as max_lenght → models.CharField shouldn't accept a string as max_length | 
|---|
comment:4 by , 10 years ago
| Triage Stage: | Unreviewed → Accepted | 
|---|
follow-up: 6 comment:5 by , 10 years ago
Is there a reason why we can't cast max_length to an integer value in Field.__init__?
comment:6 by , 10 years ago
Replying to bmispelon:
Is there a reason why we can't cast
max_lengthto an integer value inField.__init__?
Because that will mask the real "problem" as has happened with the current implementation that casts  mask_length   at  _check_max_length_attribute .
IMHO, Django shouldn't handle user's fault but warn the user about it.
comment:7 by , 10 years ago
| Cc: | added | 
|---|
Related to #20440.