django-loginas icon indicating copy to clipboard operation
django-loginas copied to clipboard

Send user_id with POST

Open pix666 opened this issue 7 years ago • 2 comments
trafficstars

Sorry for my English.

I'm trying to add "Login as" buttons to admin changelist and faced with the complexity associated with the fact that user_id passed via URL. If you will pass it as POST parameter, you will have the opportunity to use single form with multiple buttons like this: <button form="loginas-form" name="user_id" value="{{ user.id }}">Login as {{ user.username }}</button>

pix666 avatar Dec 20 '17 22:12 pix666

Ah, yes, that's a good idea. Would you like to submit a PR that will accept both?

skorokithakis avatar Dec 21 '17 12:12 skorokithakis

you can add login as button by overriding changelist view like this:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.template import Template, Context
from loginas.views import user_login
from .models import User

@admin.register(User)
class UserModelAdmin(UserAdmin):
    change_form_template = 'loginas/change_form.html'
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'login_as')
  
    # render button
    def login_as(self, user: User):
        if user.is_superuser:
            return
        t = Template("""
            {% load i18n %}
            <button class='button' type='submit' name='login-as' value='{{ user.id }}'>
                <i class="icon-user icon-alpha75"></i>
                {% trans "Log in as user" %}
            </button>
        """)
        return t.render(Context({'user': user}))
   
    # delegate logic to the user_login view
    def changelist_view(self, request, extra_context=None):
        if 'login-as' in request.POST:
            return user_login(request, request.POST['login-as'])
        return super(UserModelAdmin, self).changelist_view(request, extra_context)

vanyakosmos avatar Mar 11 '20 11:03 vanyakosmos