Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request.session from a class-based generic view

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?

like image 1000
bcattle Avatar asked Mar 27 '12 23:03

bcattle


1 Answers

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.

like image 64
Timmy O'Mahony Avatar answered Sep 22 '22 04:09

Timmy O'Mahony