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

0le*_*leg 3 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?
Run Code Online (Sandbox Code Playgroud)

bar变量传递给的方式是post()什么?

试图将其保存为FooView的字段并通过进行访问self.bar,但这并不能解决问题。self.bar被看不到post()

knb*_*nbk 5

您应该扭转它。如果需要barin 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)
        ...
Run Code Online (Sandbox Code Playgroud)

post()在之前被调用get_context_data,这就是为什么post如果在中定义它就看不到它的原因get_context_data

  • @ h3d0然后您可能有一个没有设置bar的get方法。使用`dispatch`代替,它将为每个请求方法设置它。它始终以`.as_view()`开始,它以与基于函数的视图相同的参数调用`disptach`。从那里开始,您可以使用源代码来遵循方法流程。我经常使用[基于类的经典视图](http://ccbv.co.uk/)作为参考,非常有用。 (2认同)