Django admin option to log in as normal user

in my Django project i need to give an admin option to log in as different user from admin site. I am trying to achieve specific behaviour - admin can log in as different user on a new tab or window and will also be logged in as admin on the original browser tab. Is this possible ? Can someone advise me how to achieve such behaviour ? Any help would be appreciated. 🙏

def impersonate_link(self, obj):
        impersonate_url = reverse('impersonate_user', args=[obj.id])
        return format_html(
            '<a href="{}" onclick="window.open(\'{}\', \'_blank\', \'width=800,height=600\'); return false;">Log in as</a>',
            impersonate_url, impersonate_url
        )

I created this link in admin.py to show it next to each user record.The link leads to impersonate_user view in views.py. In the view admin just logs in as desired user, but also logs out of admin account.

@staff_member_required
def impersonate_user(request, user_id):
    user = get_object_or_404(CustomUser, id=user_id)
    login(request, user)
    return redirect('home')

I get why admin is being logged out of his account, but I really need help with achieving behaviour mentioned above.

Back to Top