Skip to content

Instantly share code, notes, and snippets.

@ajitid
Created May 7, 2018 07:46
Show Gist options
  • Save ajitid/cdc5a6c5cf6de1882c618979f0a854c0 to your computer and use it in GitHub Desktop.
Save ajitid/cdc5a6c5cf6de1882c618979f0a854c0 to your computer and use it in GitHub Desktop.
Django - Best way to create custom User models
  1. Don't use auth as app name. It is already used by Django for default User model.
  2. Overwrite default User in settings.py. If auth_email is what you named this app, then put this in settings.py:-
AUTH_USER_MODEL = 'auth_email.User'
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin
from .models import User
class UserAdmin(DefaultUserAdmin):
model = User
fieldsets = (
(None, {'fields': ('email', 'password')}),
(('Personal info'), {'fields': ('first_name', 'last_name')}),
(('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
admin.site.register(User, UserAdmin)
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Create and save a user with the given email and password.
"""
if not email:
raise ValueError('email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
username = None
email = models.EmailField(
unique=True,
error_messages={
'unique': 'This email is already being used for another account.',
},
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment