Last active
January 3, 2016 22:19
-
-
Save bruth/8528077 to your computer and use it in GitHub Desktop.
Email-based user
This file contains hidden or 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
from random import choice | |
from string import ascii_lowercase, digits | |
from django.db import transaction | |
from django.db.models import User | |
USERNAME_CHARS = ascii_lowercase + digits | |
@transaction.commit_on_success | |
def create_email_based_user(email): | |
username = generate_random_username() | |
email = User.objects.normalize_email(email) | |
user = User(username=username, email=email, is_active=False) | |
user.set_unusable_password() | |
user.full_clean() | |
user.save() | |
return user | |
def generate_random_username(length=30, max_attempts=100): | |
for i in xrange(max_attempts): | |
username = ''.join(choice(USERNAME_CHARS) for i in xrange(length)) | |
if not User.objects.filter(username=username).exists(): | |
return username | |
raise ValueError('Maximum attempts made to generate username') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment