该变量在 get_context_view()
中定义,因为它需要一个 id
来访问正确的数据库对象:
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()
的方法是什么?
试图将其保存为 FooView 的字段并通过 self.bar
访问它,但这并没有成功。 self.bar
未被 post()
最佳答案
你应该扭转它。如果你需要 post()
中的 bar
,你需要在那里创建它:
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)
...
post()
在 get_context_data
之前被调用,这就是为什么如果您在 get_context_data< 中定义
。 post
看不到它
关于python - Django:将变量从 get_context_data() 传递到 post(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28072987/