4

I'm fond of Django and use it regularly. I find most of its defaults sane, but one has always bothered me to the point that I override it on every project.

The default max length of a URLField model field is 200 characters. The docs verify this limit, but don't explain why it is the case.

class URLField(CharField):
    ...

    def __init__(self, verbose_name=None, name=None, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 200)
        ...

I override it because plenty of URLs are longer than 200 chars, especially with a query string.

I understand that though the HTTP spec does not specify a maximum length, virtually all browsers support at least 2000 characters, which to me suggests a new sane default.

Curious to dig deeper, I found the first commit to add the limit in January 2007 (#f6390e8 by @jacobian); it's been essentially unchanged since.

https://github.com/django/django/blob/f6390e8983dd364053078cc80361cb369b667690/django/db/models/fields/init.py#L805

Going back even further, I discovered what I think is the version of the code mapping field types to database column types for the ORM (#f69cf70 by @adrianholovaty). The file for MySQL for example exists in May 2006 with the same 200-character limit since Django 0.95:

https://github.com/django/django/blob/f69cf70ed813a8cd7e1f963a14ae39103e8d5265/django/db/backends/mysql/creation.py#L28

Community
  • 1
  • 1
Taylor D. Edmiston
  • 12,088
  • 6
  • 56
  • 76
  • "plenty of URLs are longer than 200 chars" Which studies have you based this on? – Ignacio Vazquez-Abrams Dec 11 '15 at 00:10
  • 4
    @IgnacioVazquez-Abrams I haven't referenced a particular study, just something I've experienced practically -- one case was building an app with a social feed that saved expanded URLs from tweets. – Taylor D. Edmiston Dec 11 '15 at 00:17
  • @IgnacioVazquez-Abrams if only one url is longer than 200 chars, it is enough reason to say that 200 chars isn't enough. – GwynBleidD Dec 11 '15 at 10:53
  • @Taylor Edmiston - can you provide a direction on how to override the setting. I am running into this issue. – MikeF Dec 15 '20 at 19:10
  • 1
    @MikeF Sure, you can override it like this: `URLField(max_length=1000, ...)`. https://docs.djangoproject.com/en/3.1/ref/models/fields/#urlfield – Taylor D. Edmiston Dec 15 '20 at 20:56

1 Answers1

5

I can't say why the original max length was chosen, you would have to ask the authors of the patches you found. Note that MySQL restricts unique var chars to 255 characters, so choosing 200 avoids this problem.

Once the limit was chosen, changing it would have backwards compatibility issues. Since migrations were added in Django 1.7, it would be easier to make a change like this. If you feel strongly about changing it, the Django developers mailing list or ticket tracker is probably a better place to ask than stack overflow.

You might find the discussion on ticket 19515 interesting.

Alasdair
  • 298,606
  • 55
  • 578
  • 516