Last active
April 4, 2016 18:41
-
-
Save jkbrzt/7db3664deaa58c10ced3 to your computer and use it in GitHub Desktop.
Sane email-as-username Django setup
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
# 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