从基于类的通用视图获取request.session [英] Get request.session from a class-based generic view
问题描述
有没有办法从基于类的视图中获取 request.session
?
Is there a way to get request.session
from inside a class-based view?
例如,我有django.views.generic的
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())
我可以想到的唯一的事情是覆盖 as_view
添加
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?
推荐答案
您可以访问 self.request
从课堂内的任何地方(因此 self.request.session
)
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
这个工作的关键部分是当基于类的视图是被称为,各种有用的东西都存储在自己身上;以及请求(self.request),它包括根据URLconf捕获的位置(self.args)和基于名称的(self.kwargs)参数。
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.
这篇关于从基于类的通用视图获取request.session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!