Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...