Cots
Cots

Reputation: 13

Can I rely on self.request in django class-based views?

I see code all the time that relies on using an instance variable to get the request, like:

class MyView():
    def get(self, request):
        return foo()

    def foo():
        request = self.request
        return bar(request)

My question is, can I rely on self.request being set for every view instance? I can't find anything in the documentation that even references this attribute, and while I see it being set in some places in the source I can't tell if it is always being set.

Upvotes: 1

Views: 545

Answers (1)

wim
wim

Reputation: 363233

The request is set at a fundamental level in Django's generic view base, here, which every other kind of view derives from.

You should be perfectly safe accessing the request attribute provided you're inheriting a Django class-based view of some sort. If you have some AttributeError, it's probably because you forgot to inherit from a Django view (as in the example code posted in the question).

Upvotes: 1

Related Questions