Accessing Request Object in Form Definition

148 views
Skip to first unread message

Chris Kavanagh

unread,
Feb 22, 2016, 8:56:58 PM2/22/16
to Django users
I'm trying to understand how overriding the Constructor of a Form (forms.Form or model.Models) allows you to access the Request Object?  How does overriding __init__ allow one access to the Request?
I've looked at BaseForm and don't see the Request in the Constructor. So, I don't get it. I thought the Request Object could only be accessed in Views, basically. Any help is greatly appreciated, or a point in the right direction.

Ex:

class MyForm(forms.Form):

def __init__(self, request, *args, **kwargs):

self._my_request = request super(MyForm, self).__init__(*args, **kwargs)



PS: It;s been years since I've used this group, if I've not posted the question, my apologies.



Chris Kavanagh

unread,
Feb 23, 2016, 1:23:17 AM2/23/16
to Django users
To possibly answer my own question, thinking out loud, we have to override the Form Constructor so we can pass in the Request from the view when instantiating the Form?

James Schneider

unread,
Feb 23, 2016, 1:50:57 AM2/23/16
to django...@googlegroups.com
On Mon, Feb 22, 2016 at 10:23 PM, Chris Kavanagh <cka...@gmail.com> wrote:
To possibly answer my own question, thinking out loud, we have to override the Form Constructor so we can pass in the Request from the view when instantiating the Form?

You beat me to it. Yes, you would need to override __init__() to include the request in to your form class. Be sure to keep it out of your args/kwargs that are passed on to your super() call, though, as it will confuse the parent form class (if I remember correctly when I did the same thing). If you are using CBV's, that you'll need to override get_form() as well in order to return the form with the self.request as one of the arguments being passed in.

-James

Chris Kavanagh

unread,
Feb 23, 2016, 2:01:49 PM2/23/16
to Django users
Thank you so much, James. . .I greatly appreciate you taking the time to answer!
Reply all
Reply to author
Forward
0 new messages