Skip to content

Instantly share code, notes, and snippets.

@haxoza
Created April 17, 2015 09:03
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save haxoza/7921eaf966a16ffb95a0 to your computer and use it in GitHub Desktop.
Save haxoza/7921eaf966a16ffb95a0 to your computer and use it in GitHub Desktop.
Django custom user model & custom admin
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from .models import *
from forms import UserChangeForm, UserCreationForm
class UserAdmin(auth_admin.UserAdmin):
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name', 'twitter', 'photo', 'event')}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
limited_fieldsets = (
(None, {'fields': ('email',)}),
('Personal info', {'fields': ('first_name', 'last_name', 'twitter', 'photo')}),
('Important dates', {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
form = UserChangeForm
add_form = UserCreationForm
change_password_form = auth_admin.AdminPasswordChangeForm
list_display = ('email', 'first_name', 'last_name', 'is_superuser')
list_filter = ('event', 'is_staff', 'is_superuser', 'is_active', 'groups')
search_fields = ('first_name', 'last_name', 'email')
ordering = ('email',)
readonly_fields = ('last_login', 'date_joined',)
from django import forms
from django.contrib.auth import forms as auth_forms
from models import User
class UserCreationForm(forms.ModelForm):
error_messages = {
'password_mismatch': "The two password fields didn't match.",
}
password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput,
help_text="Enter the same password as above, for verification.")
class Meta:
model = User
fields = ('email',)
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
class UserChangeForm(forms.ModelForm):
password = auth_forms.ReadOnlyPasswordHashField(label="Password",
help_text="Raw passwords are not stored, so there is no way to see "
"this user's password, but you can change the password "
"using <a href=\"password/\">this form</a>.")
class Meta:
model = User
fields = '__all__'
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
f = self.fields.get('user_permissions', None)
if f is not None:
f.queryset = f.queryset.select_related('content_type')
def clean_password(self):
return self.initial["password"]
from django.db import models
from django.contrib.auth import models as auth_models
class UserManager(auth_models.BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email, password=password)
user.is_superuser = user.is_staff = True
user.save(using=self._db)
return user
class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
event = models.ForeignKey('Event', null=True, blank=True, related_name='organizers')
twitter = models.CharField(max_length=50, null=False, blank=True)
photo = models.ImageField(upload_to='event/organizers/', null=True, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'Organizer'
verbose_name_plural = 'Organizers'
ordering = ('id', )
def __unicode__(self):
return u'{0} ({1})'.format(self.get_full_name(), self.email)
def get_short_name(self):
return self.first_name
def get_full_name(self):
return u'{0} {1}'.format(self.first_name, self.last_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment