Search code examples
djangodjango-users

Django redirect shortcut changes request.user


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.


Solution

  • 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.