Django从另一个基于类的视图调用基于类的视图

时间:2013-02-19 11:44:21

标签: python django django-class-based-views

我正在尝试调用基于类的视图,我能够做到,但由于某种原因,我没有得到我正在调用的新类的上下文

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)

我做错了什么人?

2 个答案:

答案 0 :(得分:41)

而不是

ShowAppsView.as_view()(self.request)

我必须这样做

return ShowAppsView.as_view()(self.request)

答案 1 :(得分: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)

确保您获得的上下文是您想要的mixin中的上下文。

*编辑* 我不知道您找到compute_context的位置,但它不是django属性,因此只能从ShowAppsView.get()调用,而不会在ManageAppView调用。

相关问题