在Django Admin中使用带有自定义__init__的表单

时间:2014-11-16 17:32:20

标签: python django django-forms django-admin

我使用下面的代码在Django Admin中添加自定义表单:

class MyAdmin(admin.ModelAdmin):
    form = MyForm

但是,表单有一个重写的构造函数:

def __init__(self, author, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.author = author

如何将Admin当前用户传递给表单构造函数?

1 个答案:

答案 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