从基于类的通用视图中获取 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?
例如,我有
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?
推荐答案
您可以从班级内的任何位置访问 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 上;以及请求 (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屋!