Skip to content

Instantly share code, notes, and snippets.

@jkbrzt
Last active April 4, 2016 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkbrzt/7db3664deaa58c10ced3 to your computer and use it in GitHub Desktop.
Save jkbrzt/7db3664deaa58c10ced3 to your computer and use it in GitHub Desktop.
Sane email-as-username Django setup
# models.py
from django.core.exceptions import ValidationError
from django.core.validators import EmailValidator
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
def _user_clean(user):
"""
Require the value of `username` to be an email. The `email` field
then adopts the value from `username`.
"""
if user.username:
validator = EmailValidator('Username has to be a valid email')
validator(user.username)
if user.email and user.username != user.email:
raise ValidationError('Email must be the same as username.')
user.email = user.username
User.clean = _user_clean
@receiver(pre_save, sender=User)
def enforce_user_clean(sender, instance=None, **kwargs):
"""
Make sure our validation logic is invoked every time a user gets saved.
(The default is to only validate when a model form is used.)
"""
instance.clean()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment