简体   繁体   中英

Current user in django admin

I've tried numerous methods of finding the current user ID in django's administration. I've tried pulling the user ID via SessionKey and request.user (HTTPRequest) to no avail. My latest incarnation is:

def save(self, request, obj, form, change):
    if getattr(obj, 'submitter', None) is None:
        obj.submitter = request.user
    obj.save()

    super(AppAdmin, self).save()

in admin.py and

submitter = models.ForeignKey(User, null=True, blank=True, related_name="submitter")

in models.py. I found this elsewhere on stack overflow, but it doesn't seem to work. Any help is appreciated.

Thanks!

From the looks of your snippet, you are trying to save the currently logged in user to your model field in a ModelAdmin

It looks like you meant to override save_model

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model

class AppAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.submitter = request.user # no need to check for it.
        obj.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM