Skip to content

Instantly share code, notes, and snippets.

@darwinsalinas
Forked from lightstrike/admin.py
Created January 15, 2020 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save darwinsalinas/8dc11fe12b103bd3a7f8df185620207d to your computer and use it in GitHub Desktop.
Save darwinsalinas/8dc11fe12b103bd3a7f8df185620207d to your computer and use it in GitHub Desktop.
Custom User Admin
from django import forms
from django.contrib import admin
from django.utils.translation import ugettext as _
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput)
password2 = forms.CharField(
label='Password confirmation',
widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
msg = "Passwords don't match"
raise forms.ValidationError(msg)
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 = 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 = ('password',)
def clean_password(self):
return self.initial["password"]
class CustomUserAdmin(UserAdmin):
add_form = UserCreationForm
form = UserChangeForm
list_display = ('id', 'email')
list_filter = ('is_superuser', 'groups')
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Info', {'fields': ('first_name', 'last_name', 'headshot',)}),
('Permissions', {'fields': ('is_active',
'is_superuser',
'is_staff',
'groups',
'user_permissions')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}),
)
admin.site.register(User, CustomUserAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment