Skip to content

Instantly share code, notes, and snippets.

@eloyz
Created June 24, 2011 14:59
Show Gist options
  • Save eloyz/1044957 to your computer and use it in GitHub Desktop.
Save eloyz/1044957 to your computer and use it in GitHub Desktop.
Validate Django user max length object against database
from django.contrib.auth.models import User
from django.db.models.fields import FieldDoesNotExist
# Used for user import feature.
# There's no form validation; so we validate max_length this way.
# loop through user properties; truncate at max_length
for key, value in user.__dict__.items():
max_length = None
try:
max_length = User._meta.get_field_by_name(key)[0].max_length
except FieldDoesNotExist as e:
if max_length: # truncate per max_length field attribute
setattr(user, key, value[:max_length])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment