Django:将变量从get_context_data()传递到post() [英] Django: Passing variable from get_context_data() to post()

查看:46
本文介绍了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 <中定义它,则看不到它的原因/code>.

post() is called before get_context_data, that's why post doesn't see it if you define it in get_context_data.

这篇关于Django:将变量从get_context_data()传递到post()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆