Skip to content

Instantly share code, notes, and snippets.

@Skirmantas
Created August 13, 2011 15:32
Show Gist options
  • Save Skirmantas/1143957 to your computer and use it in GitHub Desktop.
Save Skirmantas/1143957 to your computer and use it in GitHub Desktop.
Username maxlength hack for ``django.contrib.auth``
This code is a suggested answer to question asked on Stackoverflow:
http://stackoverflow.com/questions/4827965/can-i-change-djangos-auth-user-username-field-to-be-100-chars-long-without-break/
# authhacks/models.py
from django.conf import settings
from authhacks import username_length
USERNAME_MAXLENGTH = getattr(settings, 'USERNAME_MAXLENGTH', 72)
username_length.hack_models()
username_length.hack_forms()
# authhacks/username_length.py
import sys
def hack_models(length=72):
from django.contrib.auth.models import User
username = User._meta.get_field("username")
username.max_length = length
hack_validators(username.validators)
def hack_forms(length=72, forms=[
'django.contrib.auth.forms.UserCreationForm',
'django.contrib.auth.forms.UserChangeForm',
'django.contrib.auth.forms.AuthenticationForm',
]):
"""
Hacks username length in django forms.
"""
for form in forms:
modulename, sep, classname = form.rpartition('.')
if not modulename in sys.modules:
__import__(modulename)
module = sys.modules[modulename]
klass = getattr(module, classname)
hack_single_form(klass, length)
def hack_single_form(form_class, length=72):
if hasattr(form_class, 'declared_fields'):
fields = form_class.declared_fields
elif hasattr(form_class, 'base_fields'):
fields = form_class.base_fields
else:
raise TypeError('Provided object: %s doesnt seem to be a valid Form or '
'ModelForm class.' % form_class)
username = fields['username']
hack_validators(username.validators)
username.max_length = length
username.widget.attrs['maxlength'] = length
def hack_validators(validators, length=72):
from django.core.validators import MaxLengthValidator
for key, validator in enumerate(validators):
if isinstance(validator, MaxLengthValidator):
validators.pop(key)
validators.insert(0, MaxLengthValidator(length))
# authhacks/__init__.py
# settings.py
INSTALLED_APPS = [
# ...
'django.contrib.auth',
'authhacks'
# ...
]
@ondrejsika
Copy link

I wrote pip package django-authhacks install pip install django-authhacks source on https://github.com/sikaondrej/django-authhacks

@tartley
Copy link

tartley commented Jul 6, 2015

I don't see django-authhacks on PyPI. Did you have to pull it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment