Created
May 5, 2014 19:58
-
-
Save tkrajina/dcf4310dd30c12253e3f to your computer and use it in GitHub Desktop.
Automatically wordwrap django model string fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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