Django: How to get current user in admin forms

后端 未结 6 1713
花落未央
花落未央 2020-11-30 00:31

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, s

6条回答
  •  没有蜡笔的小新
    2020-11-30 01:12

    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)

提交回复
热议问题