变量定义在里面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()
你应该扭转它。如果你需要bar
in post()
,您需要在那里创建它:
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
, 这就是为什么post
如果您在中定义它,则看不到它get_context_data
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)