Django:如何获取管理表单中的当前用户 [英] Django: How to get current user in admin forms

查看:108
本文介绍了Django:如何获取管理表单中的当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django的ModelAdmin中,我需要根据用户的权限显示自定义表单。有没有办法让当前的用户对象进入表单类,以便我可以在其 __ init __ 方法中自定义表单?

我认为保存当前请求在一个线程本地将是一种可能性,但这将是我最后的手段,认为我认为这是一个坏的设计方法....

解决方案

这是我最近做了一个博客:

  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
返回表单

我现在可以访问当前用户在我的 forms.ModelForm 通过访问 self.current_user



<编辑:这是一个古老的答案,最近看到,我意识到 get_form 方法应该修改d为:

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

(注意添加 * args


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....

解决方案

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)

这篇关于Django:如何获取管理表单中的当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆