如何在继承的基于类的视图中访问变量

时间:2017-09-06 20:07:31

标签: django django-views

我想知道如何运行现实检查来决定使用哪个模板文件。如何从AgencyFullView访问agency_count?我目前的回报是类型对象' AgencyFullMixin'没有属性' agency_count'

class AgencyFullMixin(ContextMixin):

    def get_context_data(self, pk, **kwargs):
        context_data = super(AgencyFullMixin, self).get_context_data(**kwargs)
        agency = Agencies.objects.filter(pk=pk)
        context_data["agency"] = agency
        agency_count = agency.count()
        context_data["agency_count"] = agency_count
        return context_data

class AgencyFullView(TemplateView, AgencyFullMixin):

    if agency_count != 0:    **<<<--- What to put here?**
        template_name = 'community_information_database/agency_full.html'
    else: 
        template_name = 'community_information_database/not_valid.html'

    def get_context_data(self, **kwargs):
        context_data = super(AgencyFullView, self).get_context_data(**kwargs)
        return context_data

2 个答案:

答案 0 :(得分:2)

如果您想以其他方式访问agency_count,那么您必须将其设置为属性。您可以在调度方法中执行此操作。

class AgencyFullMixin(ContextMixin):
    def dispatch(self, request, *args, **kwargs):
        agencies = Agencies.objects.filter(pk=self.kwargs['pk'])
        self.agency_count = agencies.count()
        return super(AgencyFullMixin, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """
        Add the agency count to the context
        """
        context = super(AgencyFullMixin, self).get_context_data(**kwargs)
        context['agency_count'] = self.agency_count
        return context

然后,您可以使用其他方法访问self.agency_count。要动态更改模板名称,您应该覆盖get_template_names

class AgencyFullView(AgencyFullMixin, TemplateView):
    def get_template_names(self):
        if self.agency_count != 0:
            template = 'community_information_database/agency_full.html'
        else: 
            template = 'community_information_database/not_valid.html'
        return [template]  # nb get_template_names must return a list

答案 1 :(得分:1)

修正:这是我正在使用的解决方案:

class AgencyFullMixin(ContextMixin):

    def get_context_data(self, pk, **kwargs):
        context_data = super(AgencyFullMixin, self).get_context_data(**kwargs)
        agency = Agencies.objects.filter(pk=pk)
        context_data["agency"] = agency
        agency_count = agency.count()
        context_data["agency_count"] = agency_count
        return context_data

class AgencyFullView(TemplateView, AgencyFullMixin):
    def get_template_names(self, **kwargs):
        agency = Agencies.objects.filter(pk=self.kwargs['pk']).filter(pk__isnull=False)
        if agency:
            return 'community_information_database/agency_full.html'
        else:
            return 'community_information_database/not_valid.html'

    def get_context_data(self, **kwargs):
        context_data = super(AgencyFullView, self).get_context_data(**kwargs)
        return context_data