Last active
December 22, 2015 06:39
-
-
Save micahhausler/6432434 to your computer and use it in GitHub Desktop.
Django User Manager
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
from django.contrib.auth.models import User, UserManager | |
from django.http import HttpResponse, HttpResponseNotFound | |
# Simple Error | |
class UserExists(Exception): | |
pass | |
# Model Manager | |
class MyUserManager(UserManager): | |
def create_user(self, email, password): | |
qs = super(MyUserManager, self).get_query_set() | |
try: | |
qs.get(email=email.lower()) | |
raise UserExists | |
except User.DoesNotExist: | |
user = super(MyUserManager, self).create_user( | |
email=email.lower(), | |
username=email, | |
password=password) | |
return user | |
# Model | |
class MyUser(User): | |
# ... Your sutff here ... | |
objects = MyUserManager() | |
# View | |
def your_view_function(request, *args, **kwargs): | |
# Do some parameter validation | |
try: | |
MyUser.objects.create_user(username, password) | |
except UserExists: | |
return HttpResponseNotFound("<h1>User exists</h1>") | |
return HttpResponse("<h1>User created!</h1>") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment