{"record":{"id":"f8207cd3a0e03a94","repo":"django/django","slug":"s-model-field-maximum-string-length-is-s-given","errorCode":null,"errorMessage":"%s model field maximum string length is %s, given %s characters.","messagePattern":"(.+?) model field maximum string length is (.+?), given (.+?) characters\\.","errorType":"validation","errorClass":"InvalidString","httpStatus":null,"severity":"warning","filePath":"django/contrib/gis/utils/layermapping.py","lineNumber":409,"sourceCode":"        \"\"\"\n        Verify if the OGR Field contents are acceptable to the model field. If\n        they are, return the verified value, otherwise raise an exception.\n        \"\"\"\n        if isinstance(ogr_field, OFTString) and isinstance(\n            model_field, (models.CharField, models.TextField)\n        ):\n            if self.encoding and ogr_field.value is not None:\n                # The encoding for OGR data sources may be specified here\n                # (e.g., 'cp437' for Census Bureau boundary files).\n                val = force_str(ogr_field.value, self.encoding)\n            else:\n                val = ogr_field.value\n            if (\n                model_field.max_length\n                and val is not None\n                and len(val) > model_field.max_length\n            ):\n                raise InvalidString(\n                    \"%s model field maximum string length is %s, given %s characters.\"\n                    % (model_field.name, model_field.max_length, len(val))\n                )\n        elif isinstance(ogr_field, OFTReal) and isinstance(\n            model_field, models.DecimalField\n        ):\n            try:\n                # Creating an instance of the Decimal value to use.\n                d = Decimal(str(ogr_field.value))\n            except DecimalInvalidOperation:\n                raise InvalidDecimal(\n                    \"Could not construct decimal from: %s\" % ogr_field.value\n                )\n\n            # Getting the decimal value as a tuple.\n            dtup = d.as_tuple()\n            digits = dtup[1]\n            d_idx = dtup[2]  # index where the decimal is","sourceCodeStart":391,"sourceCodeEnd":427,"githubUrl":"https://github.com/django/django/blob/ae25a40be07e8a749edf526df37c93e59d4a22c9/django/contrib/gis/utils/layermapping.py#L391-L427","documentation":"InvalidString (a LayerMapError subclass) raised in verify_ogr_field() when an OGR string value's length exceeds the model CharField/TextField max_length. The message reports the field name, configured max_length, and the actual character count.","triggerScenarios":"A shapefile NAME column longer than the model's CharField(max_length=50); TextField with a max_length set receiving a long blob; source data truncated differently than expected.","commonSituations":"Source data fields longer than anticipated; max_length chosen for display that's too small for raw import; upstream data enrichment increasing string lengths.","solutions":["Increase the model field's max_length (and run a migration) to fit the source data.","Pre-truncate the source column values via ogr2ogr SQL or a custom import step.","Use a TextField with no max_length for free-form strings.","Run save(strict=False) to skip over-length features and log them."],"exampleFix":"# before\nclass Model:\n    name = models.CharField(max_length=50)  # source has 80-char names\n\n# after\nclass Model:\n    name = models.CharField(max_length=120)  # then makemigrations + migrate","handlingStrategy":"validation","validationCode":"from django.contrib.gis.gdal import DataSource\n\ndef max_string_lengths(path, mapping, layer=0):\n    lyr = DataSource(path)[layer]\n    lengths = {}\n    for k, v in mapping.items():\n        if not isinstance(v, str):\n            continue\n        if v not in lyr.fields:\n            continue\n        idx = lyr.fields.index(v)\n        lengths[v] = max((len(feat[idx].value or '') for feat in lyr), default=0)\n    return lengths  # compare against model field max_length","typeGuard":"from django.db.models import CharField, TextField\n\ndef field_accepts_length(model_field, length):\n    if not isinstance(model_field, (CharField, TextField)):\n        return True\n    return model_field.max_length is None or length <= model_field.max_length","tryCatchPattern":"from django.contrib.gis.utils.layermapping import InvalidString\nlm = LayerMapping(Model, path, mapping)\nlm.save(strict=False, silent=False)  # logs over-length features and continues","preventionTips":["Size CharField.max_length to the longest observed source value (with headroom).","Use TextField (no max_length) for free-form strings.","Run save(strict=False) to skip over-length features instead of aborting."],"tags":["django","gis","layermapping","charfield","max-length","data"],"analyzedSha":"ae25a40be07e8a749edf526df37c93e59d4a22c9","analyzedAt":"2026-08-06T21:46:51.801Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}