Created
June 15, 2012 05:48
-
-
Save norioxkimura/2934878 to your computer and use it in GitHub Desktop.
Django の auth の User モデルの username の最大長を変更するハック
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
from django.conf import settings | |
from authhacks import username_length | |
USERNAME_MAXLENGTH = getattr(settings, 'USERNAME_MAXLENGTH', 75) | |
username_length.hack_models(USERNAME_MAXLENGTH) | |
username_length.hack_forms(USERNAME_MAXLENGTH) |
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 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment