0

I have an application where we have sub-classed the Django 'User' object into, say, 'AppAccount' object which has additional attributes. Now I have a view where I do the following:

appAccountObject.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, appAccountObject) 
redirect(someOtherView) 

Now according to pdb, request.user is an instance of AppAccount right after the login() call, but request.user is a Django User instance in the first line of someOtherView.

Why is the redirect call changing the User object back to the normal Django User? How can I avoid this?

Also, is the above code correct? Should adding the backend attribute be okay to bypass a call to authenticate? If not, what should the correct way of doing this be: I want to login a user automatically, without their credentials and then redirect to another view which is wrapped by a @login_required decorator.

Thanks.

Gaurav Dadhania
  • 5,167
  • 8
  • 42
  • 61

1 Answers1

1

A redirect causes a whole new request from the user's browser, hence the user object has to be fetched from the database again based on the session cookie and assigned to request.user. This happens in the authentication middleware. Unless you've written your own version of this, it's always going to use the default user class.

This is just one of the reasons why it's a bad idea to subclass User. Instead, extend it with a UserProfile class with a OneToOne relation to User.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • It's an inherited app, so subclassing User object was out of my control. We've written our own Authentication middleware that returns the AppAccount object from `authenticate`, yet it still seems to return `User`. Any clue why that might be happening? – Gaurav Dadhania Jul 22 '12 at 16:53
  • Nevermind, changing the `backend` attribute to our custom Auth Backend, made sure we were able to bypass the call to `authenticate` as well the correct Object instance was part of `request` after the redirect. – Gaurav Dadhania Jul 22 '12 at 17:54