[Django]-How can I get current logged User id in Django Admin Panel?

8👍

Don’t do that in the form. Override the save_model method on your admin subclass – it has access to the request.

class MessageAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super(MessageAdmin, self).save(request, obj, form, change)

0👍

Edit: Daniel’s way is better.

In your view:

user = request.user
if user.is_authenticated():
    user_id=user.pk # pk means primary key

But you don’t usually deal with the ID. Set the User field to be the object, not the id. Here’s a snippet from something I’m working on at the moment:

def question_submit(request):
    u = request.user
    if u.is_authenticated():
        if q.is_valid():
            f=q.save(commit=False)
            f.user=u
            f.save()

            return JsonResponse({'success': True})

0👍

to avoid ERROR --- 'super' object has no attribute 'save' To resolve use ---

use this:

def save_model(self, request, obj, form, change):
    obj.user = request.user
    super(MessageAdmin, self).save_model(request, obj, form, change)

Leave a comment