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

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

问题描述:

我使用以下代码在Django Admin中添加一个自定义表单:

I use the code below to add a custom form in Django Admin:

class MyAdmin(admin.ModelAdmin):
    form = MyForm

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

However, the form has an overridden constructor:

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

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

How could I pass the Admin current user to the form constructor?

更改您的 MyAdmin 类如下: / p>

change your MyAdmin class like this:

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

You can now access the current user in your forms.ModelForm by accessing 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