Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access request object from class based view

Tags:

python

django

I have code like below

url(r'login$', views.LoginView.as_view(), name='login'),

and view as follows

class LoginView(TemplateView):
    def __init__(self, *args, **kwargs):
        #How to operate on request Object's type and its params.

I have mentioned my question as comment in code.

like image 658
Exception Avatar asked Oct 20 '25 04:10

Exception


1 Answers

As mentioned by @karthikr you shouldn't be overriding __init__(). The request object is first available in the dispatch() method, which is called immediately after __init__(), but you shouldn't need to override that method either. Its primary purpose is to call the get(), post(), or other relevant method handlers. Generally speaking, however, it's not necessary to override those either.

If you really absolutely must catch the request at the earliest point possible though, then the dispatch method is your best bet.

class LoginView(TemplateView):
    def dispatch(self, request, *args, **kwargs):
        print self.request  # Works!
        return super(LoginView, self).dispatch(request, *args, **kwargs)  # Don't forget this
like image 77
Joey Wilhelm Avatar answered Oct 22 '25 17:10

Joey Wilhelm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!