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

35 投票
2 回答
30138 浏览
提问于 2025-04-17 16:21

我正在尝试调用一个基于类的视图,我已经成功做到了,但不知道为什么我没有得到我调用的新类的上下文。

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 个回答

1

当你开始在Python中使用多重继承时,事情就变得复杂了,因为你可能会把一个上下文搞混了,尤其是当它来自一个继承的混合类时。

你没有明确说明你想要获取哪个上下文,也没有定义一个新的上下文,所以很难完全诊断问题。不过,你可以尝试调整混合类的顺序;

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中被调用。

58

不是这样

ShowAppsView.as_view()(self.request)

我必须这样做

return ShowAppsView.as_view()(self.request)

撰写回答