2013-02-19 217 views
20

我想调用基于类的视图,我能够做到这一点,但由于某种原因,我没有得到我打电话给我的新班级的背景从另一个基于类的视图Django调用基于视图

class ShowAppsView(LoginRequiredMixin, CurrentUserIdMixin, TemplateView): 
    template_name = "accounts/thing.html" 



    @method_decorator(csrf_exempt) 
    def dispatch(self, *args, **kwargs): 
     return super(ShowAppsView, self).dispatch(*args, **kwargs) 

    def get(self, request, username, **kwargs): 
     u = get_object_or_404(User, pk=self.current_user_id(request)) 

     if u.username == username: 
      cities_list=City.objects.filter(user_id__exact=self.current_user_id(request)).order_by('-kms') 
      allcategories = Category.objects.all() 
      allcities = City.objects.all() 
      rating_list = Rating.objects.filter(user=u) 
      totalMiles = 0 
      for city in cities_list: 
       totalMiles = totalMiles + city.kms 

     return self.render_to_response({'totalMiles': totalMiles , 'cities_list':cities_list,'rating_list':rating_list,'allcities' : allcities, 'allcategories':allcategories}) 


class ManageAppView(LoginRequiredMixin, CheckTokenMixin, CurrentUserIdMixin,TemplateView): 
    template_name = "accounts/thing.html" 

    def compute_context(self, request, username): 
     #some logic here       
     if u.username == username: 
      if request.GET.get('action') == 'delete': 
       #some logic here and then: 
       ShowAppsView.as_view()(request,username) 

我在做什么错家伙?

+1

这是什么应该做的事情?通过简单地调用这个视图,你希望达到什么目的?我猜你可能需要返回调用它的结果,但由于'compute_context'是一个非标准方法,所以很难确定。 – 2013-02-19 11:47:31

+0

我是一种“刷新”我的网页,所以我回想起我的上一页有一些新的上下文数据 – psychok7 2013-02-19 11:50:00

+0

我正在返回返回self.render_to_response(self.compute_context(请求,用户名)) – psychok7 2013-02-19 11:50:27

回答

38

而不是

ShowAppsView.as_view()(self.request) 

我不得不这样做

return ShowAppsView.as_view()(self.request) 
+4

我发现,如果你这样做 ShowAppsView.as_view()(请求,* ARGS,** kwargs) 它实际上是有可能通过与ContextMixin,他们表现为自我get_context_data方法来获得指定参数和kwargs .args和self.kwargs。这对于重写此方法以及为表单添加上下文非常有用。 – Sven 2014-04-10 22:33:25

+0

我觉得这在功能视图中也很有用。与上面的代码,我可以从函数视图调用基于类的视图。 – 2015-01-21 08:47:44

1

当你在python中开始使用multiple inheritance时,事情会变得更加复杂,因此你可以很容易地用继承的mixin来践踏你的上下文。你不太清楚你得到了哪个上下文以及你想要哪个(你没有定义新的上下文),所以很难完全诊断,但是尝试重新调整mixin的顺序;

class ShowAppsView(LoginRequiredMixin, CurrentUserIdMixin, TemplateView): 

这意味着LoginRequiredMixin将要继承一流的,所以它会优先于其他人,如果有你要找的属性 - 如果它不是那么Python会看在CurrentUserIdMixin等等。

如果你想真正确保你得到你后的情况下,你可以添加替代像

def get_context(self, request): 
    super(<my desired context mixin>), self).get_context(request) 

,以确保您获得的上下文是从混入一个你想。

*编辑* 我不知道你发现compute_context,但它不是一个Django的属性,这样只会从ShowAppsView.get(),从来没有在ManageAppView被调用。

+0

我编辑我的代码上面,并拿出compute_context,但它仍然无法正常工作。我应该从ShowAppSview继承ManageAppView以访问该方法吗? – psychok7 2013-02-19 12:06:17

+0

同上@Daniel Roseman如果'compute_context'是你想要返回的东西,你将需要它。这是非标准的,所以也许应该在'get_context'或类似的地方。我没有提供完整的解决方案,而是一个探索/调查的途径。 – danodonovan 2013-02-19 12:12:03