Skip to content

Instantly share code, notes, and snippets.

@Brick85
Created December 3, 2015 14:24
Show Gist options
  • Save Brick85/21fb3ff4a7653ddfd3ab to your computer and use it in GitHub Desktop.
Save Brick85/21fb3ff4a7653ddfd3ab to your computer and use it in GitHub Desktop.
Django email as username
### models.py
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
class AbstractUserEmail(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True, error_messages={'unique': _("A user with that username already exists.")})
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'))
is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
class User(AbstractUserEmail):
pass
#### admin_forms.py
from django.db import models
from django import forms
from accounts.models import User
from django.utils.translation import ugettext_lazy as _
class UserCreationForm(forms.ModelForm):
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput(render_value=True))
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(render_value=True), help_text=_("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("email", "member")
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
#### admin.py
from accounts.models import User
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as UserAdminOrig
from django.contrib.auth.models import Group
from django.utils.translation import ugettext_lazy as _
from accounts.admin_forms import UserCreationForm
admin.site.unregister(Group)
class UserAdmin(UserAdminOrig):
readonly_fields = ('last_login', 'date_joined')
list_display = ('email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_active', 'member')
fieldsets = (
(None, {'fields': ('email', 'password', 'last_login', 'date_joined')}),
(_('Personal info'), {'fields': ('first_name', 'last_name',)}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
ordering = ('email',)
add_form = UserCreationForm
admin.site.register(User, UserAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment