2013-02-19 192 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