admin.py 1.39 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from .models import User


class MyUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = User


class MyUserCreationForm(UserCreationForm):

    error_message = UserCreationForm.error_messages.update({
        'duplicate_username': 'This username has already been taken.'
    })

    class Meta(UserCreationForm.Meta):
        model = User

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])


@admin.register(User)
class MyUserAdmin(AuthUserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm
    fieldsets = (
            ('User Profile', {'fields': (
                'name', 'city', 'state', 'country', 'race',
38
                'gender', 'occupation', 'biography', 'image', 'accepted_terms',
39 40 41 42 43
            )}),
    ) + AuthUserAdmin.fieldsets
    list_display = ('id', 'username', 'name', 'email', 'is_superuser')
    list_display_links = ('id', 'username')
    search_fields = ['id', 'name', 'email', 'username']
Bruno Martin's avatar
Bruno Martin committed
44
    readonly_fields = ['date_joined',]