Django:将变量从get_context_data()传递到post()
该变量在 get_context_view()
内部定义,因为它需要 id
才能访问正确的数据库对象:
The variable is defined inside get_context_view()
since it requires an id
to access correct database object:
class FooView(TemplateView):
def get_context_data(self, id, **kwargs):
---
bar = Bar.objects.get(id=id)
---
def post(self, request, id, *args, **kwargs):
# how to access bar?
# should one call Bar.objects.get(id=id) again?
将 bar
变量传递给 post()
的方式是什么?
What would be the way to pass bar
variable to post()
?
试图将其保存为FooView的字段并通过 self.bar
进行访问,但这并不能解决问题. post()
Tried to save it as FooView's field and access it via self.bar
, but this doesn't do the trick. self.bar
is not seen by post()
您应该将其反转.如果需要在 post()
中使用 bar
,则需要在此处创建它:
You should reverse it. If you need bar
in post()
, you need to create it there:
class FooView(TemplateView):
def get_context_data(self, **kwargs):
bar = self.bar
def post(self, request, id, *args, **kwargs):
self.bar = Bar.objects.get(id=id)
...
在 get_context_data
之前调用
post()
,这就是为什么 post
如果在 get_context_data .
post()
is called before get_context_data
, that's why post
doesn't see it if you define it in get_context_data
.