39

Is there a way to get request.session from inside a class-based view?

For instance, I have

from django.views.generic.edit import FormView

class CreateProfileView(FormView):
    def form_valid(self, form):
        # --> would like to save form contents to session here

        return redirect(self.get_success_url())

The only thing I can think of would be override as_view by adding

def as_view(self, request, *args, **kwargs):
    self.session = request.session
    super(CreateProfileView, self).as_view(request, *args, **kwargs)

to the class. But that seems ugly. Is there another way?

bcattle
  • 12,115
  • 6
  • 62
  • 82

1 Answers1

71

You have access to self.request from anywhere within the class (and therefore self.request.session)

https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-display/#dynamic-filtering

The key part to making this work is that when class-based views are called, various useful things are stored on self; as well as the request (self.request) this includes the positional (self.args) and name-based (self.kwargs) arguments captured according to the URLconf.

SuperFunkyMonkey
  • 495
  • 4
  • 13
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • 9
    The important part here is "when class-based views are *called*"; i.e., it needs to be done within one of the class's *methods* (e.g., def get_context_data(self, **kwargs)), not inside the class but outside any methods. – Chirael Feb 04 '15 at 02:32