4

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?

Bryson
  • 1,186
  • 2
  • 13
  • 26
  • why do you want it to be identical to the email field. Why not just some random string would work? – Irfan Jun 19 '11 at 15:19

1 Answers1

4

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:

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
  • It's kind of funny what one has to do to overcome that limitation -- I very much appreciate this solution, it's inventive without being too tacky. Thanks. – fish2000 May 21 '12 at 21:32
  • This *recipe* dates back quite some time. Maybe there's a better way to do it nowadays. – miku May 21 '12 at 21:46
  • New to me at any rate -- if you're looking for something different, custom User objects are doable w/o monkey patching or signal abuse: see http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ – fish2000 May 21 '12 at 21:57