Skip to content

Instantly share code, notes, and snippets.

@tkrajina
Created May 5, 2014 19:58
Show Gist options
  • Save tkrajina/dcf4310dd30c12253e3f to your computer and use it in GitHub Desktop.
Save tkrajina/dcf4310dd30c12253e3f to your computer and use it in GitHub Desktop.
Automatically wordwrap django model string fields
import textwrap as mod_textwrap
import django.db.models.fields as mod_fields
def wordwrap_fields(model):
"""
When models are not created through forms (so standard form validation didn't prevent
too long strings), this can be used to automatically wordwrap.
"""
for field in model._meta.fields:
name = field.name
if field.__class__ == mod_fields.CharField:
max_length = field.max_length
value = getattr(model, name)
if value:
value = mod_textwrap.wrap(value, max_length)[0]
setattr(model, name, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment