Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django proxy User model example

Tags:

python

django

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!

like image 205
Ludo Avatar asked Aug 05 '14 17:08

Ludo


Video Answer


1 Answers

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.

like image 162
Edward D'Souza Avatar answered Sep 21 '22 01:09

Edward D'Souza