Django get_context_data永远不会在MyCustomTemplateView中被调用?

时间:2022-03-24 20:58:22

EDIT: I've completely misunderstood the right way to subclass TemplateView, which is at the basis of this error. I over rid the get method as well - which I shouldn't have in a TemplateView.

编辑:我完全误解了正确的子类TemplateView的方法,这是这个错误的基础。我也完全摆脱了get方法 - 我不应该在TemplateView中使用它。

Original question:

I have created a subclass of TemplateView:

我创建了TemplateView的子类:

class MyTemplateView(TemplateView):

  def get_context_data(self,*args, **kwargs):
    context = super(MyTemplateView, self).get_context_data(*args, **kwargs)
    context['current_business_view'] = self.kwargs.get('user_business_id')
    return context

All my Views subclass MyTemplateView.

我的所有视图都是MyTemplateView的子类。

I was expecting that get_context_data was going to be called, but it looks like it never gets called - what am I missing here?

我期待get_context_data将被调用,但看起来它永远不会被调用 - 我在这里缺少什么?

1 个解决方案

#1


1  

I think the function is called but the value of user_business_id is None.

我认为函数被调用但user_business_id的值为None。

Try debugging with Python debugger.

尝试使用Python调试器进行调试。

class MyTemplateView(TemplateView):

  def get_context_data(self,*args, **kwargs):
      context = super(MyTemplateView, self).get_context_data(*args, **kwargs)
      context['current_business_view'] = self.kwargs.get('user_business_id')
      import pdb; pdb.set_trace();
      return context

Now when you do python manage.py runserver the server will stop at the breakpoint. You can type print context to see what's in the context.

现在,当你执行python manage.py runserver时,服务器将在断点处停止。您可以键入打印上下文以查看上下文中的内容。

Hope this helps.

希望这可以帮助。

#1


1  

I think the function is called but the value of user_business_id is None.

我认为函数被调用但user_business_id的值为None。

Try debugging with Python debugger.

尝试使用Python调试器进行调试。

class MyTemplateView(TemplateView):

  def get_context_data(self,*args, **kwargs):
      context = super(MyTemplateView, self).get_context_data(*args, **kwargs)
      context['current_business_view'] = self.kwargs.get('user_business_id')
      import pdb; pdb.set_trace();
      return context

Now when you do python manage.py runserver the server will stop at the breakpoint. You can type print context to see what's in the context.

现在,当你执行python manage.py runserver时,服务器将在断点处停止。您可以键入打印上下文以查看上下文中的内容。

Hope this helps.

希望这可以帮助。