开发者

Current user in django admin

开发者 https://www.devze.com 2023-02-16 00:30 出处:网络
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 开发者_Sta

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 开发者_StackOverflow社区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()
0

精彩评论

暂无评论...
验证码 换一张
取 消