Django: How to get current user in admin forms

Bernhard Vallant picture Bernhard Vallant · May 19, 2010 · Viewed 28.8k times · Source

In Django's ModelAdmin I need to display forms customized according to the permissions an user has. Is there a way of getting the current user object into the form class, so that i can customize the form in its __init__ method?
I think saving the current request in a thread local would be a possibility but this would be my last resort think I'm thinking it is a bad design approach....

Answer

Joshmaker picture Joshmaker · Jan 21, 2011

Here is what i did recently for a Blog:

class BlogPostAdmin(admin.ModelAdmin):
    form = BlogPostForm

    def get_form(self, request, **kwargs):
         form = super(BlogPostAdmin, self).get_form(request, **kwargs)
         form.current_user = request.user
         return form

I can now access the current user in my forms.ModelForm by accessing self.current_user

EDIT: This is an old answer, and looking at it recently I realized the get_form method should be amended to be:

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

(Note the addition of *args)