5

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?

Ivan
  • 1,477
  • 3
  • 18
  • 36

1 Answers1

6

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

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
Hasan Ramezani
  • 5,004
  • 24
  • 30
  • But then I need to remove the "author" parameter from the __init__ method otherwise I get an error. I would like to keep the parameter. – Ivan Nov 17 '14 at 10:31
  • @Ivan you can pass `author` parameter to form `__init__` in `def get_form` – Hasan Ramezani Nov 17 '14 at 11:19
  • Could you add an example to see how to add `author` to the `__init__` method from `get_form`? – Ivan Dec 07 '14 at 21:32