代码之家  ›  专栏  ›  技术社区  ›  copser

自定义计算返回“NoneType”对象不可调用django

  •  0
  • copser  · 技术社区  · 6 年前

    我正在为我的系统做一些计算,我需要得到一个 superuser 像这样

    location = LocationData.objects.filter(email=self.request.user.email).count() ,

    然后我需要计算该用户的所有许可证,就像这样

    count = MyUser.objects.filter(location_count=self.request.user.email).count() ,

    我需要检查一下 location == count 以及 * 有价格的地点,

    if count == location:
           context['social'] = location * FRISTPRICE
    

    当我得到价格,我需要显示在模板上。

    完整的视图是

    class AdminDashboard(TemplateView):
        """
        """
        template_name = 'administration/admin.html'
    
        @cached_property
        def get_context_data(self, **kwargs):
            context = super(AdminDashboard, self).get_context_data(**kwargs)
            user = MyUser.objects.get(pk=self.request.user.pk)
    
        # check if user is superuser if not don't include him
            if user.is_superuser:
                # check how much locations does user have
                location = LocationData.objects.filter(email=self.request.user.email).count()
    
                # check how much user have licences payed for
                count = MyUser.objects.filter(location_count=self.request.user.email).count()
    
                # if count is == to location then the location is proper
                # so count * package = application sales
                if count == location:
                    context['first_package'] = location * FIRSTPRICE
    
                if count == location:
                    context['second_package'] = location * SECONDPRICE
    
                if count == location:
                    context['third_package'] = location * THIRDPRICE
    
                return context
    

    完全错误是 HERE ,我的第一个猜测是上下文不能返回,并且这个计算不好,所以可以有人帮助我理解为什么我会得到这个错误,谢谢。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Alasdair    6 年前

    get_context_data 如果用户不是超级用户,则不返回任何内容。要修复它,请取消缩进返回上下文行:

    @cached_property
    def get_context_data(self, **kwargs):
        context = super(AdminDashboard, self).get_context_data(**kwargs)
        user = MyUser.objects.get(pk=self.request.user.pk)
    
    # check if user is superuser if not don't include him
        if user.is_superuser:
            # check how much locations does user have
            location = LocationData.objects.filter(email=self.request.user.email).count()
    
            # check how much user have licences payed for
            count = MyUser.objects.filter(location_count=self.request.user.email).count()
    
            # if count is == to location then the location is proper
            # so count * package = application sales
            if count == location:
                context['first_package'] = location * FIRSTPRICE
    
            if count == location:
                context['second_package'] = location * SECONDPRICE
    
            if count == location:
                context['third_package'] = location * THIRDPRICE
    
        return context