我使用下面的代码在Django Admin中添加自定义表单:
class MyAdmin(admin.ModelAdmin):
form = MyForm
但是,表单有一个重写的构造函数:
def __init__(self, author, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.author = author
如何将Admin当前用户传递给表单构造函数?
答案 0 :(得分:3)
像这样更改你的MyAdmin
课程:
class MyAdmin(admin.ModelAdmin):
form = MyForm
def get_form(self, request, **kwargs):
form = super(MyAdmin, self).get_form(request, **kwargs)
form.current_user = request.user
return form
您现在可以通过访问forms.ModelForm
来访问self.current_user
中的当前用户。
def __init__(self, author, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.author = author
# access to current user by self.current_user