python - Django:将变量从 get_context_data() 传递到 post()

标签 python django

该变量在 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/

相关文章:

python - 具有彩色高度的 Matplotlib 3D 瀑布图

python - 从正在运行的 Python3 session 中激活 virtualenv

python - 使用 django 进行 mp3 流传输的问题

python - 使用 Itertools 实现具有内部中断的可变级别嵌套循环

python - Python egg 模块名的鲁棒检测

python - Python中重置时间序列的调整图

django - pip install mod_wsgi 在 vi​​rtualenv 中失败

django-rest-framework用于ContentType对象的序列化器

python - 为查询集的下标元素赋值不起作用

Django模板调用函数