31

クラスベースのビューを呼び出そうとしていますが、それを実行できますが、何らかの理由で、呼び出している新しいクラスのコンテキストを取得できません

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)

私は何をしているのですか?

4

2 に答える 2

55

それ以外の

ShowAppsView.as_view()(self.request)

私はこれをしなければならなかった

return ShowAppsView.as_view()(self.request)
于 2013-02-19T12:32:02.777 に答える
1

Python で多重継承を使い始めると事態はさらに複雑になるため、継承された mixin からのコンテキストを簡単に踏みにじることができます。

どのコンテキストを取得していて、どのコンテキストを必要としているかはよくわかりません (新しいコンテキストを定義しているわけではありません)。そのため、完全に診断することは困難ですが、ミックスインの順序を並べ替えてみてください。

class ShowAppsView(LoginRequiredMixin, CurrentUserIdMixin, TemplateView):

これLoginRequiredMixinは、継承元の最初のクラスになることを意味するため、探している属性がある場合は他のクラスよりも優先されます-そうでない場合は、python が検索さCurrentUserIdMixinれます。

目的のコンテキストを確実に取得したい場合は、次のようなオーバーライドを追加できます

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

取得するコンテキストが必要な mixin のものであることを確認します。

*編集* どこで見つけたのかわかりませんがcompute_context、django属性ではないため、からのみ呼び出されShowAppsView.get()ManageAppView.

于 2013-02-19T11:54:21.447 に答える