views:

62

answers:

1

My original though was to simply put the email address into both username and email fields when creating accounts, this doesn't work as Django limits the username field to 30 characters which may not be enough for email addresses.

My second thought was to md5 the email address, put the hash into username, and that would make it always unique (and technically, identical to the email field as well). md5 is 32 characters, again I only have 30 characters to work with.

My third thought was to chop the last two characters off the end of the md5 hash, making it 30 and then using it as I had planned to use it with the full hash. But I don't know what the chances are of ending up with two hashes that are identical up to the 30th character and only differing at 31 and 32, which I've chopped off.

Is there a better way to relate the contents of the username field to the email address, in a way that will make it always unique?

+2  A: 

We developed a django application, which stores emails as usernames. Django builtin username model is restricted to 30 chars, which was good for 90%.

To support longer usernames, without altering the django source, we used a tiny additional application, called longer_username:

from django.db.models.signals import class_prepared

def longer_username(sender, *args, **kwargs):
    # You can't just do `if sender == django.contrib.auth.models.User`
    # because you would have to import the model
    # You have to test using __name__ and __module__
    if sender.__name__ == "User" and sender.__module__ == \
        "django.contrib.auth.models":
        sender._meta.get_field("username").max_length = 75

class_prepared.connect(longer_username)

We added this as the first application into INSTALLED_APPS:

INSTALLED_APPS = (
    'longer_username',
    ...
)

That's it. More information can be found here:

The MYYN