示例#1
0
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PoliticianDetailView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the institutions
        context['institution_list'] = Institution.objects.all()

        # is the user monitoring the act?
        context['is_user_monitoring'] = False
        try:
            if self.request.user.is_authenticated():
                # add a monitoring form, to context,
                # to switch monitoring on and off
                context['monitoring_form'] = MonitoringForm(
                    data={
                        'content_type_id': context['person'].content_type_id,
                        'object_pk': context['person'].id,
                        'user_id': self.request.user.id
                    })

                if context['person'] in self.request.user.get_profile(
                ).monitored_objects:
                    context['is_user_monitoring'] = True
        except ObjectDoesNotExist:
            context['is_user_monitoring'] = False
        return context
示例#2
0
def object_inline_monitoring(context, object, shows_monitoring_users=True):
    args = {
        'object': object,
        'shows_monitoring_users': shows_monitoring_users,
        'user': context['user'],
        'is_user_monitoring': False,
        'login_url_with_redirect': context['login_url'],
    }
    # is the user monitoring the act?
    try:
        if args['user'].is_authenticated():
            # add a monitoring form, to context,
            # to switch monitoring on and off
            args['monitoring_form'] = MonitoringForm(
                data={
                    'content_type_id': object.content_type_id,
                    'object_pk': object.id,
                    'user_id': args['user'].id
                })

            if object in args['user'].get_profile().monitored_objects:
                args['is_user_monitoring'] = True
    except ObjectDoesNotExist:
        args['is_user_monitoring'] = False

    return args
示例#3
0
    def post(self, request, *args, **kwargs):
        # chek if current user has a profile
        try:
            current_user_profile = request.user.get_profile()
        except ObjectDoesNotExist:
            current_user_profile = False

        if current_user_profile:
            try:
                monitoring = Monitoring.objects.get(
                    content_type=ContentType.objects.get(
                        pk=request.POST['content_type_id']),
                    object_pk=request.POST['object_pk'],
                    user=request.user)
                form = MonitoringForm(request.POST, instance=monitoring)
                if form.is_valid():
                    monitoring.delete()
                    return HttpResponseRedirect(self.get_success_url())
                else:
                    return self.form_invalid(form)
            except ObjectDoesNotExist:
                return self.form_invalid()
        else:
            return HttpResponseRedirect(self.get_success_url())
示例#4
0
    def post(self, request, *args, **kwargs):
        # chek if current user has a profile
        try:
            current_user_profile = request.user.get_profile()
        except ObjectDoesNotExist:
            current_user_profile = False

        if current_user_profile:
            try:
                monitoring = Monitoring.objects.get(
                    content_type=ContentType.objects.get(pk=request.POST['content_type_id']),
                    object_pk=request.POST['object_pk'],
                    user=request.user
                )
                form = MonitoringForm(request.POST, instance=monitoring)
                if form.is_valid():
                    monitoring.delete()
                    return HttpResponseRedirect(self.get_success_url())
                else:
                    return self.form_invalid(form)
            except ObjectDoesNotExist:
                return self.form_invalid()
        else:
            return HttpResponseRedirect(self.get_success_url())
示例#5
0
def object_monitoring(context, object, show_politicians=True):

    object_type = object._meta.verbose_name
    if object_type.lower() == 'tag':
        object_type = "l'argomento"
    if object_type.lower() == 'categoria':
        object_type = "la categoria"
    if object_type.lower() == 'persona':
        object_type = "il politico"
    if object_type.lower() in [
            'delibera', 'mozione', 'interrogazione', 'interpellanza'
    ]:
        object_type = "l'atto"

    args = {
        'object': object,
        'object_type': object_type,
        'user': context['user'],
        'is_user_monitoring': False,
        'show_politicians': show_politicians,
        'login_url_with_redirect': context['login_url'],
    }
    # is the user monitoring the act?
    try:
        if args['user'].is_authenticated():
            # add a monitoring form, to context,
            # to switch monitoring on and off
            args['monitoring_form'] = MonitoringForm(
                data={
                    'content_type_id': object.content_type_id,
                    'object_pk': object.id,
                    'user_id': args['user'].id
                })

            if object in args['user'].get_profile().monitored_objects:

                args['is_user_monitoring'] = True
    except ObjectDoesNotExist:
        args['is_user_monitoring'] = False

    return args
示例#6
0
    def get_context_data(self, **kwargs):
        # the monitored act
        # it's a deliberation, not an act, from the urls
        act = self.get_object()

        # call the base implementation first to get a context
        context = super(ActDetailView, self).get_context_data(**kwargs)
        # mix-in tab-related context
        self.tab = self.kwargs.get('tab', 'default')
        extra_context = getattr(self,
                                'get_related_%(tab)s' % {'tab': self.tab})()
        if extra_context:
            context.update(extra_context)

        if self.request.user.has_perm('acts.change_act'):
            # add a form for editing title of act
            context['title_form'] = ActTitleForm(
                initial={
                    'id': act.pk,
                    'adj_title': act.adj_title or act.title,
                })

        if self.request.user.has_perm('locations.change_taggedactbylocation'):
            # add a form for classifying an act using locations
            context['location_form'] = ActLocationsAddForm(
                initial={
                    'act': act,
                    'locations': act.locations,
                })

        # add a form for the description of the act
        signers = [p.person for p in act.presenters]
        try:
            if self.request.user.is_authenticated() and\
               self.request.user.get_profile().person and \
               self.request.user.get_profile().person in signers:
                context['description_form'] = ActDescriptionForm(
                    initial={
                        'id': act.pk,
                        'description': act.description,
                    })
        except ObjectDoesNotExist:
            context['description_form'] = False

        # is the user monitoring the act?
        context['is_user_monitoring'] = False
        try:
            if self.request.user.is_authenticated():
                # add a monitoring form, to context,
                # to switch monitoring on and off
                context['monitoring_form'] = MonitoringForm(
                    data={
                        'content_type_id': act.content_type_id,
                        'object_pk': act.id,
                        'user_id': self.request.user.id
                    })

                if act in self.request.user.get_profile().monitored_objects:
                    context['is_user_monitoring'] = True
        except ObjectDoesNotExist:
            context['is_user_monitoring'] = False

        # some user can edit categories and tags
        if self.request.user.has_perm('taxonomy.change_taggedact'):
            # all categories and tags
            context['topics'] = {
                'categories': Category.objects.all(),
                'tags': Tag.objects.all()
            }

        context['n_documents'] = act.attachment_set.count()
        context['n_votes'] = act.votation_set.count()
        context['n_amendments'] = act.amendment_set.count()
        context['n_speeches'] = len(act.speeches)

        # retrieve a dictionary with status and its transitions
        context['act_type'] = act._meta.verbose_name
        context['transition_groups'] = act.get_transitions_groups()

        # default public date and idnum
        # may be override for approved acts (see Deliberation and CGDeliberation)
        context['public_date'] = act.presentation_date
        context['public_idnum'] = act.idnum

        # some user can set transitions
        if self.request.user.has_perm(
                'acts.change_transition'):  #and context['status_list']
            context['transition_forms'] = {}
            if len(context['transition_groups']) == 5:
                context['transition_forms'][
                    'transition_to_council_form'] = ActTransitionForm(
                        initial={
                            'act': act,
                            'final_status': 'COUNCIL'
                        },
                        prefix="council")
                context['transition_forms'][
                    'transition_to_committee_form'] = ActTransitionForm(
                        initial={
                            'act': act,
                            'final_status': 'COMMITTEE'
                        },
                        prefix="committee")
            context['transition_forms'][
                'transition_to_final_form'] = ActFinalTransitionForm(
                    initial={'act': act}, prefix="final")
            context['transition_forms']['transition_to_final_form'].fields[
                'final_status'].widget.choices = act.FINAL_STATUSES

        return context
示例#7
0
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PoliticianDetailView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the institutions
        context['institution_list'] = Institution.objects.all()

        context['resources'] = {}

        person = self.object

        context['person'] = person

        charge = self.get_charge()

        context['charge'] = charge

        for r in person.resources.values('resource_type', 'value',
                                         'description'):
            context['resources'].setdefault(r['resource_type'], []).append({
                'value':
                r['value'],
                'description':
                r['description']
            })

        past_charges = person.get_past_institution_charges()
        context['past_charges'] = past_charges

        current_charges = person.get_current_institution_charges().exclude(
            institutionresponsability__charge_type__in=(
                InstitutionResponsability.CHARGE_TYPES.mayor, ),
            institutionresponsability__end_date__isnull=True)
        context['current_charges'] = current_charges
        context['current_institutions'] = current_charges.values(
            "institution__name").distinct()
        context[
            'current_committee_charges'] = person.get_current_committee_charges(
            )
        #        context['is_counselor'] = person.is_counselor()
        #        context['current_counselor_charge'] = person.current_counselor_charge()

        context['current_groupcharge'] = person.current_groupcharge

        if charge:
            historical_groupcharges = charge.historical_groupcharges  #person.historical_groupcharges
            context[
                'historical_groupcharges'] = historical_groupcharges.order_by(
                    'start_date') if historical_groupcharges else None

        # Is the current charge a counselor? If so, we show present/absent graph
        if charge and charge.is_counselor:
            # Calculate average present/absent for counselors
            percentage_present = 0
            percentage_absent = 0
            n_counselors = len(municipality.council.charges)
            for counselor in municipality.council.charges:
                n_votations = counselor.n_present_votations \
                    + counselor.n_absent_votations
                if n_votations > 0:
                    percentage_present += \
                        float(counselor.n_present_votations) / n_votations
                    percentage_absent += \
                        float(counselor.n_absent_votations) / n_votations
            # Empty city council? That can't be the case!
            # n_counselors is supposed to be > 0
            if n_counselors > 0:
                context['percentage_present_votations_average'] = \
                    "%.1f" % (float(percentage_present) / n_counselors * 100)
                context['percentage_absent_votations_average'] = \
                    "%.1f" % (float(percentage_absent) / n_counselors * 100)
            else:
                context['percentage_present_votations_average'] = 0
                context['percentage_absent_votations_average'] = 0

            # Calculate present/absent for current counselor
            charge.percentage_present_votations = charge.percentage_absent_votations = 0.0

            if charge.n_present_votations + charge.n_absent_votations > 0:
                context[
                    'n_total_votations'] = charge.n_present_votations + charge.n_absent_votations
                context['percentage_present_votations'] = \
                    "%.1f" % (float(charge.n_present_votations) /\
                              context['n_total_votations'] * 100.00)
                context['percentage_absent_votations'] = \
                    "%.1f" % (float(charge.n_absent_votations) /\
                              context['n_total_votations'] * 100.00)

            if charge.n_present_votations > 0:
                context['percentage_rebel_votations'] = "%.1f" % (
                    float(100 * charge.n_rebel_votations) /
                    charge.n_present_votations)

            # Current politician's charge votes for key votations
            # last 10 are passed to template
            context['current_charge_votes'] = charge.chargevote_set \
                .filter(votation__is_key=True) \
                .order_by('-votation__sitting__date','votation__idnum')[0:10]

            context['current_charge_rebel_votes'] = charge.chargevote_set \
                .filter(is_rebel=True) \
                .order_by('-votation__sitting__date','votation__idnum')[0:10]

        # Is the current charge a counselor? If so, we show present/absent
        # graph
        if charge and charge.is_in_city_government:

            # Calculate average present/absent for counselors
            percentage_present = 0
            percentage_absent = 0
            n_gov_charges = len(municipality.gov.charges)
            for gov_charge in municipality.gov.charges:
                n_attendances = gov_charge.n_present_attendances \
                    + gov_charge.n_absent_attendances
                if n_attendances > 0:
                    percentage_present += \
                        float(gov_charge.n_present_attendances) / n_attendances
                    percentage_absent += \
                        float(gov_charge.n_absent_attendances) / n_attendances
            # Empty city council? That can't be the case!
            # n_counselors is supposed to be > 0
            if n_gov_charges > 0:
                context['percentage_present_attendances_average'] = \
                    "%.1f" % (float(percentage_present) / n_gov_charges * 100)
                context['percentage_absent_attendances_average'] = \
                    "%.1f" % (float(percentage_absent) / n_gov_charges * 100)
            else:
                context['percentage_present_attendances_average'] = 0
                context['percentage_absent_attendances_average'] = 0

            # Calculate present/absent for current charge
            charge.percentage_present_attendances = charge.percentage_absent_attendances = 0.0

            if charge.n_present_attendances + charge.n_absent_attendances > 0:
                context[
                    'n_total_attendances'] = charge.n_present_attendances + charge.n_absent_attendances
                context['percentage_present_attendances'] = \
                    "%.1f" % (float(charge.n_present_attendances) * 100 / context['n_total_attendances'])
                context['percentage_absent_attendances'] = \
                    "%.1f" % (float(charge.n_absent_attendances) * 100 / context['n_total_attendances'])

        # last 10 presented acts
        presented_acts = Act.objects\
            .filter(actsupport__charge=charge)\
            .order_by('-presentation_date')
        context['n_presented_acts'] = presented_acts.count()
        context['presented_acts'] = presented_acts[0:10]

        act_types = [Deliberation, CGDeliberation, Motion, Agenda, \
            Interrogation, Interpellation, Audit, Amendment]

        context['act_types'] = []

        for act_type in act_types:

            context['act_types'].append({
                'name' : act_type.__name__.lower(),
                'verbose_name' : act_type._meta.verbose_name,
                'total' : act_type.objects.filter(actsupport__charge=charge).count(),
                'non_final' : act_type.objects.filter(actsupport__charge=charge)\
                                  .filter(~ Q(status__in=(s[0] for s in act_type.FINAL_STATUSES)))\
                                  .count(),
            })

        # charge speeches
        speeches = SearchQuerySet().filter(django_ct='acts.speech')\
            .filter(charge = charge.id)\
            .order_by('-date')

        context['n_speeches'] = speeches.count()
        context['speeches'] = speeches[0:5]

        # is the user monitoring the act?
        context['is_user_monitoring'] = False
        try:
            if self.request.user.is_authenticated():
                # add a monitoring form, to context,
                # to switch monitoring on and off
                context['monitoring_form'] = MonitoringForm(
                    data={
                        'content_type_id': person.content_type_id,
                        'object_pk': person.id,
                        'user_id': self.request.user.id
                    })

                if person in self.request.user.get_profile().monitored_objects:
                    context['is_user_monitoring'] = True
        except ObjectDoesNotExist:
            context['is_user_monitoring'] = False

        #
        # extract all the topics of the acts presented
        # by the person in the view
        #

        # get the person from the view
        p = person  #self.object

        person_topics = []
        person_topic_tag_ids = set([])
        person_topic_category_ids = set([])

        for charge in p.all_institution_charges:

            for act in charge.presented_acts.select_related().order_by(
                    "-presentation_date")[0:50]:
                for topic in act.topics.select_related():

                    # avoid repetitions, by skipping categories and tags already appended
                    if topic.category_id in person_topic_category_ids \
                            and topic.tag_id in person_topic_tag_ids:
                        continue

                    # append topic


#                    context['person_topics'].append(topic)
                    person_topics.append(topic)
                    person_topic_tag_ids.add(topic.tag_id)
                    person_topic_category_ids.add(topic.category_id)

        context['person_topics'] = person_topics
        """
        # Obscurated form of the above code :-)

        for topics in [y.topics for x in person.get_current_institution_charges() for y in x.presented_act_set.all() ]:
            for topic in topics:
                if topic.category in [t.category for t in context['person_topics']]:
                    if topic.tag in [t.tag for t in context['person_topics']]:
                        continue
                context['person_topics'].append(topic)
        """

        return context
示例#8
0
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PoliticianDetailView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the institutions
        context['institution_list'] = Institution.objects.all()

        context['resources'] = dict((r['resource_type'], {
            'value': r['value'],
            'description': r['description']
        }) for r in self.object.resources.values('resource_type', 'value',
                                                 'description'))
        context[
            'current_charges'] = self.object.get_current_institution_charges(
            ).exclude(institutionresponsability__charge_type__in=(
                InstitutionResponsability.CHARGE_TYPES.mayor, ),
                      institutionresponsability__end_date__isnull=True)
        context[
            'current_committee_charges'] = self.object.get_current_committee_charges(
            )
        context['is_counselor'] = self.object.is_counselor()
        context[
            'current_counselor_charge'] = self.object.current_counselor_charge(
            )

        context['current_groupcharge'] = self.object.current_groupcharge

        historical_groupcharges = self.object.historical_groupcharges
        context['historical_groupcharges'] = historical_groupcharges.order_by(
            'start_date') if historical_groupcharges else None

        # Is politician a counselor? If so, we show present/absent
        # graph
        if context['is_counselor']:
            # Calculate average present/absent for counselors
            percentage_present = 0
            percentage_absent = 0
            n_counselors = len(municipality.council.charges)
            for counselor in municipality.council.charges:
                n_votations = counselor.n_present_votations \
                    + counselor.n_absent_votations
                if n_votations > 0:
                    percentage_present += \
                        float(counselor.n_present_votations) / n_votations
                    percentage_absent += \
                        float(counselor.n_absent_votations) / n_votations
            # Empty city council? That can't be the case!
            # n_counselors is supposed to be > 0
            context['percentage_present_votations_average'] = \
                "%.1f" % (float(percentage_present) / n_counselors * 100)
            context['percentage_absent_votations_average'] = \
                "%.1f" % (float(percentage_absent) / n_counselors * 100)

            # Calculate present/absent for current counselor
            charge = context['current_counselor_charge']
            charge.percentage_present_votations = charge.percentage_absent_votations = 0.0

            if charge.n_present_votations + charge.n_absent_votations > 0:
                context[
                    'n_total_votations'] = charge.n_present_votations + charge.n_absent_votations
                context['percentage_present_votations'] = \
                    "%.1f" % (float(charge.n_present_votations) /\
                              context['n_total_votations'] * 100.00)
                context['percentage_absent_votations'] = \
                    "%.1f" % (float(charge.n_absent_votations) /\
                              context['n_total_votations'] * 100.00)

            context['percentage_rebel_votations'] = "%.1f" % (float(
                100 * charge.n_rebel_votations / charge.n_present_votations))

        # Current politician's charge votes for key votations
        # last 10 are passed to template
        charge = context['current_counselor_charge']
        if charge:
            context['current_charge_votes'] = charge.chargevote_set \
                .filter(votation__is_key=True) \
                .order_by('-votation__sitting__date')[0:10]

        # last 10 presented acts
        presented_acts = Act.objects\
            .filter(actsupport__charge__pk__in=self.object.current_institution_charges)\
            .order_by('-presentation_date')
        context['n_presented_acts'] = presented_acts.count()
        context['presented_acts'] = presented_acts[0:10]

        # is the user monitoring the act?
        context['is_user_monitoring'] = False
        try:
            if self.request.user.is_authenticated():
                # add a monitoring form, to context,
                # to switch monitoring on and off
                context['monitoring_form'] = MonitoringForm(
                    data={
                        'content_type_id': context['person'].content_type_id,
                        'object_pk': context['person'].id,
                        'user_id': self.request.user.id
                    })

                if context['person'] in self.request.user.get_profile(
                ).monitored_objects:
                    context['is_user_monitoring'] = True
        except ObjectDoesNotExist:
            context['is_user_monitoring'] = False

        context['person_topics'] = []

        #
        # extract all the topics of the acts presented by the person in the view
        #

        # get the person from the view
        p = self.object
        for charge in p.current_institution_charges:
            for act in charge.presented_acts:
                for topic in act.topics:

                    # avoid repetitions, by skipping categories and tags already appended
                    if topic.category in [
                            t.category for t in context['person_topics']
                    ]:
                        if topic.tag in [
                                t.tag for t in context['person_topics']
                        ]:
                            continue

                    # append topic
                    context['person_topics'].append(topic)
        """
        # Obscurated form of the above code :-)

        for topics in [y.topics for x in self.object.get_current_institution_charges() for y in x.presented_act_set.all() ]:
            for topic in topics:
                if topic.category in [t.category for t in context['person_topics']]:
                    if topic.tag in [t.tag for t in context['person_topics']]:
                        continue
                context['person_topics'].append(topic)
        """

        return context