I extend the django user model as described in the dev doc. I wan't to keep most of the original User model features so I extend the AbstractUser class. I've defined in settings.py:
AUTH_USER_MODEL = 'myapp.CustomUser'
My user class:
class CustomUser(AbstractUser):
custom_field = models.ForeignKey('OtherModel')
objects = UserManager()
Everything seems to work fine but when I try to make it managed by the admin site:
admin.site.register(CustomUser, UserAdmin)
I get this error on the admin CustomUser creation page (after validation of the password confirmation form):
AttributeError: Manager isn't available; User has been swapped for 'myapp.CustomUser'
The point is that I need this model managed by the admin site in order to have the same creation process as with the original User model (two step process with password validation).
You need only change form for adding user(overwrite clean_username and change User on get_user_model()
Full working example(If you inherited from AbstractUser)
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class MyUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
class MyUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
def clean_username(self):
username = self.cleaned_data["username"]
try:
get_user_model().objects.get(username=username)
except get_user_model().DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
fieldsets = (
(None, {'fields': [('username', 'password'),]}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
admin.site.register(MyUser, MyUserAdmin)
I struggled with this error for hours. For me I needed to remove all references to
from django.contrib.auth.models import User
and then replace it with:
from myapp.models import MyUser as User
This is assuming your custom User model is in an app called myapp
and you called the model MyUser
.
I'm using as User
so that I don't have to change where my existing code that makes reference to the the User
object from django.contrib.auth.models
.
Good luck!
Alan
@aviars
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With