Created
February 9, 2017 19:27
-
-
Save lightstrike/01a2a4adc4828d61dea4e5cf963d29a0 to your computer and use it in GitHub Desktop.
Custom User Admin
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 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
for future reference, you can copy and past, except for the headshot field in line 67.