Get request.session from a class-based generic view
Asked Answered
O

1

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?

Octavla answered 27/3, 2012 at 23:22 Comment(0)
S
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.

Swashbuckler answered 27/3, 2012 at 23:30 Comment(1)
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.Gearhart

© 2022 - 2024 — McMap. All rights reserved.