I'm trying to add some custom logic to my Django User model and am trying to do so using a proxy User model.
I have a model something like this:
from django.contrib.auth.models import User
class CustomUser(User):
def custom_method(self):
return 'Something'
class Meta:
proxy = True
If I omit the AUTH_USER_MODEL setting then I'm able to run a Django shell and use CustomUser quite happily, however, I presumed I'd be able to set AUTH_USER_MODEL in my settings, so that this was the default user across my app (like when you use a totally custom user model), but this isn't the case, and when I try and run with AUTH_USER_MODEL set I get:
TypeError: CustomUser cannot proxy the swapped model 'myapp.CustomUser'
Is this possible? Thanks!
Setting AUTH_USER_MODEL
to a custom class, and using a proxy model are two different approaches to customizing Django's User model behaviour. You're seeing that error because you're mixing them together, which doesn't make sense.
Approach 1:
If you set AUTH_USER_MODEL='myapp.CustomUser'
then you shouldn't proxy anything. Define your custom user model like so:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
Approach 2:
Proxy the Django user model as you have above. Don't set AUTH_USER_MODEL
. In your code, make sure you're always importing and using your CustomUser class.
Between the two approaches, #2 is preferred if you're starting a new project because it gives you the most control. However, if you already have a running project migrating to a different model is a little tricky and so approach #1 with a proxy might be the best you can do.
See https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model for more details.
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