Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to get current user in admin forms?

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 because I'm thinking it is a bad design approach.

like image 248
Bernhard Vallant Avatar asked May 19 '10 11:05

Bernhard Vallant


People also ask

How does Django get current user information?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting. request. user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.

How do I get to the admin page in Django?

To login to the site, open the /admin URL (e.g. http://127.0.0.1:8000/admin ) and enter your new superuser userid and password credentials (you'll be redirected to the login page, and then back to the /admin URL after you've entered your details).


2 Answers

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)

like image 52
Joshmaker Avatar answered Oct 11 '22 20:10

Joshmaker


Joshmaker's answer doesn't work for me on Django 1.7. Here is what I had to do for Django 1.7:

class BlogPostAdmin(admin.ModelAdmin):     form = BlogPostForm      def get_form(self, request, obj=None, **kwargs):         form = super(BlogPostAdmin, self).get_form(request, obj, **kwargs)         form.current_user = request.user         return form 

For more details on this method, please see this relevant Django documentation

like image 24
sid-kap Avatar answered Oct 11 '22 20:10

sid-kap