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

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

问题描述

在 Django 的 ModelAdmin 中,我需要显示根据用户拥有的权限定制的表单.有没有办法将当前用户对象放入表单类中,以便我可以在其 __init__ 方法中自定义表单?

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.

推荐答案

这是我最近为一个博客所做的:

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

我现在可以通过访问 self.current_user

这是一个旧答案,最近看它我意识到get_form方法应该修改为:

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

(注意添加了*args)

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

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