简体   繁体   中英

Get current user in Django admin

I have a posting object that can be either accessed in the website or the admin panel. In both, the user is automatically assigned to the post when the user posts it. In the website area, it works fine. However, it does not work in the admin area. First, I tried just having the form input there. When I try to save the object and leave the input blank, it tells me the form has no value. Then, trying to see if I just put in a random value and see if it was overwritten, I did that. However, that random value was not overwritten with the current user. If I excluded the field, when I try to save the model I get an Integrity error saying the field author 'may not be NULL', so I'm assuming my save_model() function is not firing right at all. Now the code I'm using for this I've seen all over the internet and people claim for it to work, I don't know if it's just broken now or what. Here's my code:

from django.contrib import admin
from posting.models import Posting, Categories

class PostingAdmin(admin.ModelAdmin):
    list_display = ("title","author", "article","date")
    exclude = ('author',)
    fieldsets = (
        (None, {
            'fields': ('title',)
        }),
        ('Body', {
            'fields': ('article',)
            }),
    )

    def save_model(self,request,form,obj,change):
        print 'ENTERING SAVE_MODEL FUNCTION'
        if not change:
            obj.author = request.user
            print 'OBJ.AUTHOR:' + str(obj.author)
        obj.save()
        print "EXITING SAVE_MODEL FUNCTION"
admin.site.register(Posting, PostingAdmin)

You could override the ModelAdmin.get_form, by adding the request as an attribute of the newly created form class .

class EntryAdmin(admin.ModelAdmin):
    form = EntryAdminForm

    def get_form(self, request, *args, **kwargs):
        form = super(EntryAdmin, self).get_form(request, *args, **kwargs)
        form.request = request
        return form

This works for me:

from django.contrib import admin
from page.models import Page

class PageAdmin(admin.ModelAdmin):
    def get_form(self, request, *args, **kwargs):
        form = super(PageAdmin, self).get_form(request, *args, **kwargs)
        form.base_fields['author'].initial = request.user
        return form

admin.site.register(Page, PageAdmin)

I know i am a bit late for posting this solution, but like me if anyone else come across you may try:

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

I added this for information only as I came across this post which made me look deeper for an issue I was having that was similar...
To pre-populate an admin field in Django 1.11 from "request" data, see below example of a models "user" field being pre-populated with the logged in user:

admin.py

class PostingAdmin(admin.ModelAdmin):

  def get_changeform_initial_data(self, request):
    return {'user': request.user}

This populates the field when initially adding a new "Posting Admin" (model instance) before it has been saved for the first time.

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