Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - User proxy model from request

I use a proxy model on User like

class Nuser(User):
    class Meta:
        proxy = True
    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

I use it throughout my views.
I was wondering the best way to get the instance of this object for the request.user

Each time I do

Nuser.objects.get(pk=request.user.pk)

Isn't there a simpler way to do it ?

like image 654
Pierre de LESPINAY Avatar asked May 21 '12 09:05

Pierre de LESPINAY


1 Answers

You could write a custom authentication backend that returns instances of your proxy model instead of a User instance:

from django.contrib.auth.backends import ModelBackend

class ProxiedModelBackend(ModelBackend):
    def get_user(self, user_id):
        try:
            return Nuser.objects.get(pk=user_id)
        except Nuser.DoesNotExist:
            return None

In your settings.py

AUTHENTICATION_BACKENDS = ['my_project.auth_backends.ProxiedModelBackend',]
like image 194
Benjamin Wohlwend Avatar answered Oct 10 '22 08:10

Benjamin Wohlwend