Okay, this one is pretty obvious to everyone who use Django and frequently asked by newbies, but I'd like to make it clear and discuss if there are any other ways to do it. The most widespread and convenient approach now is to store email in username field as Django 1.2 allows "@", "_" and "-" characters, but this way has following issues:
max_length=30
property, which is ridiculously small for emails. Even if you override form validation, DB will have varchar(30)
instead of EmailField
's varchar(75)
unless you alter your table manually.User.email_user()
working. I think there are some other places when User.email
is used.The other approach could be authentication using email
field by passing it to your auth backend like so, but it still has problems:
authenticate(self, email=None, password=None)
User.email
doesn't have unique=True
property, which means that your DB won't have index, making your lookups by email slow like hell.username
field, which has unique=True
, by completely removing it from your table or altering it to allow NULL and removing index.Resuming, both ways are evil and require DB-specific code to be executed after syncdb, which is unacceptable if you need DB-independent application.
I've packaged up django-email-as-username which should pretty much do everything you need if you're looking to remove usernames, and only use emails.
The brief overview is:
Under the hood usernames are hashed versions of the emails, which ends up meaning we're not limited to the Django's username 30 char limit (Just the regular email 75 char limit.)
Edit: As of Django 1.5, you should look into using a custom User model instead of the 'django-email-as-username' package.
David Cramer came up with a solution to this problem that I love. I'm currently using it on a production site where the user has to be able to log in using their email OR their username. You can find it here:
Logging In With Email Addresses in Django
If the login name provided on the form is an email (contains the '@' symbol), it will attempt to authenticate with that, and will fall back on the username if it isn't an email. (Naturally, you just need to make sure your registration form captures an email for this work.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With