def field_value(revision, field):
    value = getattr(revision, field)
    if field in ['is_current', 'is_surrogate', 'no_volume',
                 'display_volume_with_number', 'no_brand',
                 'page_count_uncertain', 'title_inferred']:
        return yesno(value, 'Yes,No')
    elif field in ['publisher', 'indicia_publisher', 'brand']:
        return absolute_url(value)
    elif field in ['notes', 'tracking_notes', 'publication_notes',
                   'characters', 'synopsis', 'reprint_notes']:
        return linebreaksbr(value)
    elif field in ['url']:
        return urlize(value)
    elif field in ['indicia_pub_not_printed']:
        return yesno(value, 'Not Printed,Printed')
    elif field in ['no_editing', 'no_script', 'no_pencils', 'no_inks',
                   'no_colors', 'no_letters']:
        return yesno(value, 'X, ')
    elif field in ['page_count']:
        if revision.source_name == 'issue' and revision.changeset.storyrevisions.count():
            # only calculate total sum for issue not sequences
            sum_story_pages = format_page_count(sum_page_counts(
                              revision.changeset.storyrevisions.all()))
            return u'%s (total sum of story page counts: %s' % \
                   (format_page_count(value), sum_story_pages)
        return format_page_count(value)
    return value
Ejemplo n.º 2
0
def field_value(revision, field):
    value = getattr(revision, field)
    if field in [
            'is_current', 'is_surrogate', 'no_volume',
            'display_volume_with_number', 'no_brand', 'page_count_uncertain',
            'title_inferred'
    ]:
        return yesno(value, 'Yes,No')
    elif field in ['publisher', 'indicia_publisher', 'brand']:
        return absolute_url(value)
    elif field in [
            'notes', 'tracking_notes', 'publication_notes', 'characters',
            'synopsis', 'reprint_notes'
    ]:
        return linebreaksbr(value)
    elif field in ['url']:
        return urlize(value)
    elif field in ['indicia_pub_not_printed']:
        return yesno(value, 'Not Printed,Printed')
    elif field in [
            'no_editing', 'no_script', 'no_pencils', 'no_inks', 'no_colors',
            'no_letters'
    ]:
        return yesno(value, 'X, ')
    elif field in ['page_count']:
        if revision.source_name == 'issue' and revision.changeset.storyrevisions.count(
        ):
            # only calculate total sum for issue not sequences
            sum_story_pages = format_page_count(
                sum_page_counts(revision.changeset.storyrevisions.all()))
            return u'%s (total sum of story page counts: %s' % \
                   (format_page_count(value), sum_story_pages)
        return format_page_count(value)
    return value
Ejemplo n.º 3
0
 def __repr__(self):
     return '<%(module)s.%(cls)s version=%(version)d, ' \
            'multiple_connections=%(conns)s ' \
            'supports_faceting=%(facets)s>' % {
         'module': self.__class__.__module__,
         'cls': self.__class__.__name__,
         'conns': yesno(self.has_multiple_connections()),
         'facets': yesno(self.supports_faceting()),
         'version': self.version,
     }
Ejemplo n.º 4
0
 def __repr__(self):
     is_valid = self.is_bound and not bool(self._errors)
     return '<%(module)s.%(cls)s bound=%(is_bound)s valid=%(valid)s ' \
            'version=%(version)d multiple_connections=%(conns)s ' \
            'supports_faceting=%(facets)s>' % {
                'module': self.__class__.__module__,
                'cls': self.__class__.__name__,
                'is_bound': yesno(self.is_bound),
                'conns': yesno(self.has_multiple_connections()),
                'facets': yesno(self.should_allow_faceting()),
                'valid': yesno(is_valid),
                'version': self.haystack_config.version,
            }
Ejemplo n.º 5
0
def field_value(revision, field):
    value = getattr(revision, field)
    if field in [
            'is_surrogate', 'no_volume', 'display_volume_with_number',
            'no_brand', 'page_count_uncertain', 'title_inferred'
    ]:
        return yesno(value, 'Yes,No')
    elif field in ['is_current']:
        res_holder_display = ''
        if revision.previous():
            reservation = revision.source.get_ongoing_reservation()
            if revision.previous().is_current and not value and reservation:
                res_holder = reservation.indexer
                res_holder_display = ' (ongoing reservation held by %s %s)' % \
                  (res_holder.first_name, res_holder.last_name)
        return yesno(value, 'Yes,No') + res_holder_display
    elif field in ['publisher', 'indicia_publisher', 'brand']:
        return absolute_url(value)
    elif field in [
            'notes', 'tracking_notes', 'publication_notes', 'characters',
            'synopsis', 'reprint_notes'
    ]:
        return linebreaksbr(value)
    elif field in ['url']:
        return urlize(value)
    elif field in ['indicia_pub_not_printed']:
        return yesno(value, 'Not Printed,Printed')
    elif field in [
            'no_editing', 'no_script', 'no_pencils', 'no_inks', 'no_colors',
            'no_letters'
    ]:
        return yesno(value, 'X, ')
    elif field in ['page_count']:
        if revision.source_name == 'issue' and \
           revision.changeset.storyrevisions.count():
            # only calculate total sum for issue not sequences
            sum_story_pages = format_page_count(
                sum_page_counts(revision.changeset.storyrevisions.all()))
            return u'%s (note: total sum of story page counts is %s)' % \
                   (format_page_count(value), sum_story_pages)
        return format_page_count(value)
    elif field == 'isbn':
        if value:
            if validated_isbn(value):
                return u'%s (note: valid ISBN)' % value
            elif len(value.split(';')) > 1:
                return u'%s (note: invalid or inequal ISBNs)' % value
            elif value:
                return u'%s (note: invalid ISBN)' % value
    return value
Ejemplo n.º 6
0
def populate_initiative_pages(apps, schema_edtior):
    from pages.models import InitiativeEndorsementIndexPage, InitiativeEndorsementPage
    from endorsements.models import Initiative

    initiative_root_page = InitiativeEndorsementIndexPage.objects.get(
        title='Our Initiatives')

    for initiative in Initiative.objects.all():
        req = requests.get("http://ourrevolution.com/ballot-initiatives/%s" %
                           initiative.slug)
        try:
            html_content = BeautifulSoup(
                req.text,
                "html5lib").select('p.candidate-bio')[0].contents[0].strip()
            signup_tagline = BeautifulSoup(
                req.text, "html5lib").select('h3')[0].text.strip()
        except BaseException, e:
            print "Failed on %s: %s" % (req.url, e.message)
            continue

        page_title = "%s on %s %s: %s" % (yesno(
            initiative.vote).title(), initiative.state, initiative.title,
                                          initiative.name)

        page = InitiativeEndorsementPage(
            **{
                'title': page_title,
                'slug': initiative.slug,
                'body': html_content,
                'initiative': initiative,
                'signup_tagline': signup_tagline
                # 'content_type': ContentType.objects.get_for_model(CandidateEndorsementPage),
            })

        initiative_root_page.add_child(instance=page)
Ejemplo n.º 7
0
    def render_values(self, show_hidden=False, for_display=False):
        """
        Renders values as dict.
        """
        if not self.is_valid():
            return

        field_mapping = OrderedDict()

        fields = list(self) if show_hidden else self.visible_fields()
        fields.sort(key=id_compare)

        for field in fields:
            name = field.name
            label = field.field.label
            value = self.cleaned_data[name]

            if not isinstance(field, CaptchaField):

                if isinstance(value, bool):
                    value = yesno(value, u"%s,%s" % (_('yes'), _('no')),)
                elif isinstance(value, UploadedFile):
                    value = value.name

                if for_display:
                    field_mapping[name] = {'label': unicode(label), 'value': unicode(value)}
                else:
                    try:
                        position = int(name.split("_")[-1])
                    except:
                        position = 0
                    label = "%03d_%s" % (position, label)
                    field_mapping[label] = unicode(value)
        return field_mapping
Ejemplo n.º 8
0
def _get_data_part2(learning_unit_yr, with_attributions):
    lu_data_part2 = []
    if with_attributions:
        lu_data_part2.append(
            " \n".join(
                [_get_attribution_line(value)
                 for value in attribution_charge_new.find_attribution_charge_new_by_learning_unit_year_as_dict(
                    learning_unit_yr
                ).values()
                 ]
            )
        )

    lu_data_part2.extend([
        learning_unit_yr.get_periodicity_display(),
        yesno(learning_unit_yr.status),
        _get_significant_volume(learning_unit_yr.pm_vol_tot or 0),
        _get_significant_volume(learning_unit_yr.pm_vol_q1 or 0),
        _get_significant_volume(learning_unit_yr.pm_vol_q2 or 0),
        learning_unit_yr.pm_classes or 0,
        _get_significant_volume(learning_unit_yr.pp_vol_tot or 0),
        _get_significant_volume(learning_unit_yr.pp_vol_q1 or 0),
        _get_significant_volume(learning_unit_yr.pp_vol_q2 or 0),
        learning_unit_yr.pp_classes or 0,
        learning_unit_yr.get_quadrimester_display() or '',
        learning_unit_yr.get_session_display() or '',
        learning_unit_yr.language or "",
    ])
    return lu_data_part2
    def get_link_context(self, context, obj, fieldname, admin_site, querystring):
        """
        Adds a `link` and `verbose_name` to the context, if
        :meth:`~adminlinks.templatetags.adminlinks_buttons.BaseAdminLink.is_valid`

        :param context: Hopefully, a :class:`~django.template.RequestContext`
                        otherwise :meth:`~adminlinks.templatetags.adminlinks_buttons.BaseAdminLink.is_valid`
                        is unlikely to be :data:`True`
        :param obj: the :class:`~django.db.models.Model` instance to link to.
                    Must have a primary key, and
                    :class:`~django.db.models.Options` from which we can
                    retrieve a :attr:`~django.db.models.Field.verbose_name`
        :param fieldname: the specific model field to render a link for.
        :param admin_site: name of the admin site to use; defaults to **"admin"**
        :param querystring: a querystring to include in the link output.
                            Defaults to "_popup=1"
        :return: the link values.
        :rtype: dictionary.
        """
        ctx = {}
        ctx.update(_add_custom_link_to_context(admin_site, context['request'],
                                               obj._meta, 'change',
                                               'change_field',
                                               [obj.pk, fieldname],
                                               query=querystring))
        # successfully loaded link, add the fieldname.
        if 'link' in ctx:
            field = obj._meta.get_field(fieldname)
            value = getattr(obj, fieldname, None)
            if field.get_internal_type() in ('BooleanField', 'NullBooleanField'):
                icon = 'admin/img/icon-%s.gif' % yesno(value, "yes,no,unknown")
                ctx.update(maybe_boolean=True, img=icon)
            ctx.update(verbose_name=field.verbose_name,
                       existing_value=value)
        return ctx
Ejemplo n.º 10
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)

        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if isinstance(value, Money):
            return escape(format_money(value))

        if not value:
            value = ""

        return force_text(value)
Ejemplo n.º 11
0
def add_helpers(worksheet, row, column, event, job, helpers,
                multiple_shifts_format):
    for helper in helpers:
        row.next()
        column.reset()

        num_shifts = helper.shifts.count()
        num_jobs = len(helper.coordinated_jobs)
        format = None
        if num_shifts + num_jobs > 1:
            format = multiple_shifts_format

        worksheet.write(row.get(), column.next(), escape(helper.firstname),
                        format)
        worksheet.write(row.get(), column.next(), escape(helper.surname),
                        format)
        worksheet.write(row.get(), column.next(), escape(helper.email), format)
        if event.ask_phone:
            worksheet.write(row.get(), column.next(), escape(helper.phone),
                            format)
        if event.ask_shirt:
            worksheet.write(row.get(), column.next(),
                            escape(str(helper.get_shirt_display())), format)
        if event.ask_vegetarian:
            worksheet.write(row.get(), column.next(),
                            escape(filters.yesno(helper.vegetarian)), format)
        if job.infection_instruction:
            worksheet.write(
                row.get(), column.next(),
                escape(str(helper.get_infection_instruction_short())), format)
        worksheet.write(row.get(), column.next(), escape(helper.comment),
                        format)
Ejemplo n.º 12
0
 def _get_luy_expected_data(self, luy):
     return [
         luy.acronym,
         luy.academic_year.__str__(),
         luy.complete_title,
         luy.get_container_type_display(),
         luy.get_subtype_display(),
         luy.entity_requirement,
         '',  # Proposal
         '',  # Proposal state
         luy.credits,
         luy.entity_allocation,
         luy.complete_title_english,
         '',
         luy.get_periodicity_display(),
         yesno(luy.status),
         _get_significant_volume(luy.pm_vol_tot or 0),
         _get_significant_volume(luy.pm_vol_q1 or 0),
         _get_significant_volume(luy.pm_vol_q2 or 0),
         luy.pm_classes or 0,
         _get_significant_volume(luy.pp_vol_tot or 0),
         _get_significant_volume(luy.pp_vol_q1 or 0),
         _get_significant_volume(luy.pp_vol_q2 or 0),
         luy.pp_classes or 0,
         luy.get_quadrimester_display() or '',
         luy.get_session_display() or '',
         luy.language or "",
         "{} ({}) - {} - {}\n".format(
             self.an_education_group_parent.partial_acronym,
             "{0:.2f}".format(luy.credits),
             self.an_education_group_parent.acronym,
             self.an_education_group_parent.title)
     ]
Ejemplo n.º 13
0
 def get_html_for_value(self, value):
     if isinstance(value, bool):
         return yesno(
             value,
             '<i class="glyphicon glyphicon-ok-circle">,<i class="glyphicon glyphicon-remove-circle">'
         )
     return super(UserReport, self).get_html_for_value(value)
Ejemplo n.º 14
0
def _get_data_part2(learning_unit_yr, with_attributions):
    lu_data_part2 = []
    if with_attributions:
        lu_data_part2.append(
            " \n".join(
                [_get_attribution_line(value)
                 for value in attribution_charge_new.find_attribution_charge_new_by_learning_unit_year_as_dict(
                    learning_unit_yr
                ).values()
                 ]
            )
        )

    lu_data_part2.extend([
        learning_unit_yr.get_periodicity_display(),
        yesno(learning_unit_yr.status),
        _get_significant_volume(learning_unit_yr.pm_vol_tot or 0),
        _get_significant_volume(learning_unit_yr.pm_vol_q1 or 0),
        _get_significant_volume(learning_unit_yr.pm_vol_q2 or 0),
        learning_unit_yr.pm_classes or 0,
        _get_significant_volume(learning_unit_yr.pp_vol_tot or 0),
        _get_significant_volume(learning_unit_yr.pp_vol_q1 or 0),
        _get_significant_volume(learning_unit_yr.pp_vol_q2 or 0),
        learning_unit_yr.pp_classes or 0,
        learning_unit_yr.get_quadrimester_display() or '',
        learning_unit_yr.get_session_display() or '',
        learning_unit_yr.language or "",
    ])
    return lu_data_part2
Ejemplo n.º 15
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)

        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if not value:
            value = ""

        return force_text(value)
Ejemplo n.º 16
0
    def formatted_value(self):
        """
        Get a human-consumable value for the attribute.

        The current locale is used for formatting.

        :return: Textual value
        :rtype: str
        """
        try:
            if self.attribute.type == AttributeType.BOOLEAN:
                return yesno(self.value)
            if self.attribute.type in (AttributeType.INTEGER,
                                       AttributeType.DECIMAL):
                return format_number(self.value)
            if self.attribute.type == AttributeType.TIMEDELTA:
                a = now()
                b = a + self.value
                return timesince(a, b)
            if self.attribute.type in (AttributeType.DATETIME,
                                       AttributeType.DATE):
                return format_datetime(self.value)
        except:  # If formatting fails, fall back to string formatting.
            pass
        return six.text_type(self.value)
Ejemplo n.º 17
0
 def __repr__(self):
     is_valid = self.is_bound and not bool(self._errors)
     return (
         "<%(module)s.%(cls)s bound=%(is_bound)s valid=%(valid)s "
         "version=%(version)d multiple_connections=%(conns)s "
         "supports_faceting=%(facets)s>"
         % {
             "module": self.__class__.__module__,
             "cls": self.__class__.__name__,
             "is_bound": yesno(self.is_bound),
             "conns": yesno(self.has_multiple_connections()),
             "facets": yesno(self.should_allow_faceting()),
             "valid": yesno(is_valid),
             "version": self.guess_haystack_version(),
         }
     )
Ejemplo n.º 18
0
def truthy(value, arg=None):
    """Wraps django's yesno filter to allow for JavaScript-style true or false string values."""
    truthiness = None
    if value.lower() == 'true':
        truthiness = True
    elif value.lower() == 'false':
        truthiness = False
    return yesno(truthiness, arg)
Ejemplo n.º 19
0
def _field_extractor_function(field):
    """Return a function that extracts a given field from an instance of a model."""
    if field.choices:
        return lambda o: getattr(o, "get_%s_display" % field.name)()
    elif isinstance(field, BooleanField):
        return lambda o: yesno(getattr(o, field.name), "Yes,No")
    else:
        return lambda o: unicode(getattr(o, field.name))
Ejemplo n.º 20
0
def handle_nullboolean(field, request_get):
    """Build a list of chips for NullBooleanField field."""
    value = yesno(
        field.value(),
        pgettext_lazy('Possible values of boolean filter', 'yes,no,all'))
    return [{
        'content': CHIPS_PATTERN % (field.label, value),
        'link': get_cancel_url(request_get, field.name)}]
Ejemplo n.º 21
0
def truthy(value, arg=None):
    """Wraps django's yesno filter to allow for JavaScript-style true or false string values."""
    truthiness = None
    if value.lower() == 'true':
        truthiness = True
    elif value.lower() == 'false':
        truthiness = False
    return yesno(truthiness, arg)
Ejemplo n.º 22
0
def generate_progress_report(year):
    # create instance of mission:
    qs = models.Sample.objects.filter(season=year)

    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="herring_progress_report_{}.csv"'.format(year)
    writer = csv.writer(response)

    # write the header information
    writer.writerow(['{} Herring Progress Report'.format(year), "", "", "", "", "",
                     'Report generated on {}'.format(timezone.now().strftime('%Y-%m-%d %H:%M')), ])

    # write the header for the bottle table
    writer.writerow(["", ])

    writer.writerow([
        "Season",
        "Sample no.",
        "Type",
        "Sample date",
        "Sampler's reference no.",
        "Sampler Name",
        "Length frequencies collected",
        "Fish preserved",
        "Lab processing",
        "Otoliths processing",
    ])

    for sample in qs:
        if sample.fish_details.count():
            if sample.fish_details.last().lab_processed_date:
                lab_processed_date = sample.fish_details.last().lab_processed_date.strftime('%Y-%m-%d')
            else:
                lab_processed_date = ""
            if sample.fish_details.last().otolith_processed_date:
                otolith_processed_date = sample.fish_details.last().otolith_processed_date.strftime('%Y-%m-%d')
            else:
                otolith_processed_date = ""
        else:
            lab_processed_date = ""
            otolith_processed_date = ""

        writer.writerow(
            [
                sample.season,
                sample.id,
                sample.get_type_display(),
                sample.sample_date.strftime('%Y-%m-%d'),
                sample.sampler_ref_number,
                sample.sampler,
                yesno(sample.length_frequency_objects.count()),
                sample.total_fish_preserved,
                lab_processed_date,
                otolith_processed_date,
            ])

    return response
def field_value(revision, field):
    value = getattr(revision, field)
    if field in ['is_surrogate', 'no_volume',
                 'display_volume_with_number', 'no_brand',
                 'page_count_uncertain', 'title_inferred']:
        return yesno(value, 'Yes,No')
    elif field in ['is_current']:
        res_holder_display = ''
        if revision.previous():
            reservation = revision.source.get_ongoing_reservation()
            if revision.previous().is_current and not value and reservation:
                res_holder = reservation.indexer
                res_holder_display = ' (ongoing reservation held by %s %s)' % \
                  (res_holder.first_name, res_holder.last_name)
        return yesno(value, 'Yes,No') + res_holder_display
    elif field in ['publisher', 'indicia_publisher', 'brand']:
        return absolute_url(value)
    elif field in ['notes', 'tracking_notes', 'publication_notes',
                   'characters', 'synopsis', 'reprint_notes']:
        return linebreaksbr(value)
    elif field in ['url']:
        return urlize(value)
    elif field in ['indicia_pub_not_printed']:
        return yesno(value, 'Not Printed,Printed')
    elif field in ['no_editing', 'no_script', 'no_pencils', 'no_inks',
                   'no_colors', 'no_letters']:
        return yesno(value, 'X, ')
    elif field in ['page_count']:
        if revision.source_name == 'issue' and \
           revision.changeset.storyrevisions.count():
            # only calculate total sum for issue not sequences
            sum_story_pages = format_page_count(sum_page_counts(
                              revision.changeset.storyrevisions.all()))
            return u'%s (note: total sum of story page counts is %s)' % \
                   (format_page_count(value), sum_story_pages)
        return format_page_count(value)
    elif field == 'isbn':
        if value:
            if validated_isbn(value):
                return u'%s (note: valid ISBN)' % value
            elif len(value.split(';')) > 1:
                return u'%s (note: invalid or inequal ISBNs)' % value
            elif value:
                return u'%s (note: invalid ISBN)' % value
    return value
Ejemplo n.º 24
0
def handle_nullboolean(field, request_get):
    """Build a list of chips for NullBooleanField field."""
    value = yesno(
        field.value(),
        pgettext_lazy("Possible values of boolean filter", "yes,no,all"))
    return [{
        "content": CHIPS_PATTERN % (field.label, value),
        "link": get_cancel_url(request_get, field.name),
    }]
Ejemplo n.º 25
0
def handle_nullboolean(field, request_get):
    """Build a list of chips for NullBooleanField field."""
    value = yesno(
        field.value(),
        pgettext_lazy('Possible values of boolean filter', 'yes,no,all'))
    return [{
        'content': CHIPS_PATTERN % (field.label, value),
        'link': get_cancel_url(request_get, field.name)
    }]
Ejemplo n.º 26
0
 def __unicode__(self):
     titulacion =  yesno(self.titulado, 'titulado, no titulado')
     label = ''
     try:
         t = self.territoriocomunidadnegra
         label = "%s (%s): %s" % ('Com. Negra',titulacion, self.nombre)
     except:
         label = "%s (%s): %s" % ('Com. Indigena', titulacion, self.nombre)
     return label
Ejemplo n.º 27
0
 def __init__(self, autocomplete_url, multiple=None, attrs=None, **kwargs):
     super(InfiniteChoiceWidget, self).__init__(attrs)
     self.autocomplete_url = autocomplete_url
     self.multiple = multiple
     self.attrs = attrs
     if self.attrs is None:
         self.attrs = {}
     self.attrs['data-placeholder'] = _('Select from choices')
     self.attrs['data-required'] = yesno(kwargs.get('required'), 'true,false,false')
Ejemplo n.º 28
0
def friendly(value, null_value=None):
    if value is None and not (null_value is None):
        return null_value
    if isinstance(value, (QuerySet, list)):
        value = ", ".join(force_str(object) for object in value)
    if isinstance(value, bool):
        value = yesno(value)
    if hasattr(value, 'url'):
        value = value.url
    return force_str(value)
Ejemplo n.º 29
0
def friendly(value, null_value=None):
    if value is None and not (null_value is None):
        return null_value
    if isinstance(value, (QuerySet, list)):
        value = ", ".join(force_text(object) for object in value)
    if isinstance(value, bool):
        value = yesno(value)
    if hasattr(value, 'url'):
        value = value.url
    return force_text(value)
Ejemplo n.º 30
0
def friendly(value):
    if value in (None, "", [], (), {}):
        return None

    if type(value) is list:
        value = ", ".join(value)
    if type(value) is bool:
        value = yesno(value, u"{0},{1}".format(_("Yes"), _("No")))
    if not isinstance(value, string_types):
        value = force_text(value)
    return value
def friendly(value):
    if value in (None, '', [], (), {}):
        return None

    if type(value) is list:
        value = ', '.join(value)
    if type(value) is bool:
        value = yesno(value, u'{0},{1}'.format(_('Yes'), _('No')))
    if not isinstance(value, basestring):
        value = unicode(value)
    return value
Ejemplo n.º 32
0
def friendly(value): 
    if type(value) is QuerySet:
        qs = value
        value = []
        for object in qs:
            value.append(object.__unicode__())
    if type(value) is list:
        value = ", ".join(value)
    if type(value) is bool:
        value = yesno(value, u"%s,%s" % (_('yes'), _('no')),)
    return value
Ejemplo n.º 33
0
def handle_nullboolean(field, request_get):
    """Build a list of chips for NullBooleanField field."""
    value = yesno(
        field.value(), pgettext_lazy("Possible values of boolean filter", "yes,no,all")
    )
    return [
        {
            "content": CHIPS_PATTERN % (field.label, value),
            "link": get_cancel_url(request_get, field.name),
        }
    ]
Ejemplo n.º 34
0
def friendly(value):
    if value in (None, '', [], (), {}):
        return None

    if type(value) is list:
        value = ', '.join(value)
    if type(value) is bool:
        value = yesno(value, u'{0},{1}'.format(_('Yes'), _('No')))
    if not isinstance(value, string_types):
        value = force_text(value)
    return value
Ejemplo n.º 35
0
    def test_prepare_xls_content(self):
        entity_requirement = EntityVersion.objects.filter(entity=OuterRef(
            'learning_container_year__requirement_entity'), ).current(
                OuterRef('academic_year__start_date')).values('acronym')[:1]

        entity_allocation = EntityVersion.objects.filter(entity=OuterRef(
            'learning_container_year__allocation_entity'), ).current(
                OuterRef('academic_year__start_date')).values('acronym')[:1]

        qs = LearningUnitYear.objects.filter(
            pk=self.learning_unit_yr_1.pk).annotate(
                entity_requirement=Subquery(entity_requirement),
                entity_allocation=Subquery(entity_allocation),
            )

        result = prepare_xls_content(qs, with_grp=True, with_attributions=True)
        self.assertEqual(len(result), 1)

        luy = annotate_qs(qs).get()
        self.assertListEqual(
            result[0],
            [
                luy.acronym,
                luy.academic_year.__str__(),
                luy.complete_title,
                luy.get_container_type_display(),
                luy.get_subtype_display(),
                luy.entity_requirement,
                '',  # Proposal
                '',  # Proposal state
                luy.credits,
                luy.entity_allocation,
                luy.complete_title_english,
                '',
                luy.get_periodicity_display(),
                yesno(luy.status),
                _get_significant_volume(luy.pm_vol_tot or 0),
                _get_significant_volume(luy.pm_vol_q1 or 0),
                _get_significant_volume(luy.pm_vol_q2 or 0),
                luy.pm_classes or 0,
                _get_significant_volume(luy.pp_vol_tot or 0),
                _get_significant_volume(luy.pp_vol_q1 or 0),
                _get_significant_volume(luy.pp_vol_q2 or 0),
                luy.pp_classes or 0,
                luy.get_quadrimester_display() or '',
                luy.get_session_display() or '',
                luy.language or "",
                "{} ({}) - {} - {}\n".format(
                    self.an_education_group_parent.partial_acronym,
                    "{0:.2f}".format(
                        luy.credits), self.an_education_group_parent.acronym,
                    self.an_education_group_parent.title)
            ])
Ejemplo n.º 36
0
            def humanize(field):
                value = field['value']
                field_type = field['type']

                if value in (None, '', [], (), {}):
                    return None

                if field_type == 'checkbox':
                    value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No')))
                if field_type == 'checkbox_multiple':
                    value = ', '.join(list(value))
                return value
Ejemplo n.º 37
0
def value_for_presentation(value):
    """Convert a value ready for presentation in a template"""
    # we only deal with values that are the literals True, False, & None
    # currently.
    if value not in [True, False, None]:
        return value

    # Use Django's yesno template filter to map:
    #  * True->Yes
    #  * False->No
    #  * None->"" (empty string)
    return yesno(value, "Yes,No,")
Ejemplo n.º 38
0
            def humanize(field):
                value = field['value']
                field_type = field['type']

                if value in (None, '', [], (), {}):
                    return None

                if field_type == 'checkbox':
                    value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No')))
                if field_type == 'checkbox_multiple':
                    value = ', '.join(list(value))
                return value
Ejemplo n.º 39
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)
        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, bool):
            value = yesno(value)

        return force_text(value)
Ejemplo n.º 40
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)
        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, bool):
            value = yesno(value)

        return force_text(value)
Ejemplo n.º 41
0
def friendly(value): 
    if type(value) is QuerySet:
        qs = value
        value = []
        for object in qs:
            value.append(object.__unicode__())
    if type(value) is list:
        value = ", ".join(value)
    if type(value) is bool:
        value = yesno(value, u"%s,%s" % (_('yes'), _('no')),)
    if not isinstance(value, basestring):
        value = unicode(value)
    return value
Ejemplo n.º 42
0
 def test_yesno(self):
     self.assertEqual(yesno(True), 'yes')
     self.assertEqual(yesno(False), 'no')
     self.assertEqual(yesno(None), 'maybe')
     self.assertEqual(yesno(True, 'certainly,get out of town,perhaps'),
                      'certainly')
     self.assertEqual(yesno(False, 'certainly,get out of town,perhaps'),
                      'get out of town')
     self.assertEqual(yesno(None, 'certainly,get out of town,perhaps'),
                      'perhaps')
     self.assertEqual(yesno(None, 'certainly,get out of town'),
                      'get out of town')
Ejemplo n.º 43
0
 def test_yesno(self):
     self.assertEqual(yesno(True), 'yes')
     self.assertEqual(yesno(False), 'no')
     self.assertEqual(yesno(None), 'maybe')
     self.assertEqual(yesno(True, 'certainly,get out of town,perhaps'),
                       'certainly')
     self.assertEqual(yesno(False, 'certainly,get out of town,perhaps'),
                       'get out of town')
     self.assertEqual(yesno(None, 'certainly,get out of town,perhaps'),
                       'perhaps')
     self.assertEqual(yesno(None, 'certainly,get out of town'),
                       'get out of town')
Ejemplo n.º 44
0
def to_html(field):
    value = field["value"]
    field_type = field["type"]

    if value in (None, "", [], (), {}):
        return mark_safe("&mdash;")

    if field_type == "file":
        value = '<a href="{0}">{0}</a>'.format(value)
    if field_type == "checkbox":
        value = yesno(bool(value), u"{0},{1}".format(_("Yes"), _("No")))
    if field_type == "checkbox_multiple":
        value = ", ".join(list(value))
    return mark_safe(value)
Ejemplo n.º 45
0
def to_html(field):
    value = field['value']
    field_type = field['type']

    if value in (None, '', [], (), {}):
        return mark_safe('&mdash;')

    if field_type == 'file':
        value = '<a href="{0}">{0}</a>'.format(value)
    if field_type == 'checkbox':
        value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No')))
    if field_type == 'checkbox_multiple':
        value = ', '.join(list(value))
    return mark_safe(value)
def to_html(field):
    value = field['value']
    field_type = field['type']

    if value in (None, '', [], (), {}):
        return mark_safe('&mdash;')

    if field_type == 'file':
        value = '<a href="{0}">{0}</a>'.format(value)
    if field_type == 'checkbox':
        value = yesno(bool(value), u'{0},{1}'.format(_('Yes'), _('No')))
    if field_type == 'checkbox_multiple':
        value = ', '.join(list(value))
    return mark_safe(value)
Ejemplo n.º 47
0
def _get_optional_data(data, luy, optional_data_needed, gey):
    if optional_data_needed['has_required_entity']:
        data.append(luy.learning_container_year.requirement_entity)
    if optional_data_needed['has_allocation_entity']:
        data.append(luy.learning_container_year.allocation_entity)
    if optional_data_needed['has_credits']:
        data.append(gey.relative_credits or '-')
        data.append(luy.credits.to_integral_value() or '-')
    if optional_data_needed['has_periodicity']:
        data.append(luy.get_periodicity_display())
    if optional_data_needed['has_active']:
        data.append(str.strip(yesno(luy.status)))
    if optional_data_needed['has_quadrimester']:
        data.append(luy.get_quadrimester_display() or '')
    if optional_data_needed['has_session_derogation']:
        data.append(luy.get_session_display() or '')
    if optional_data_needed['has_volume']:
        luys = annotate_qs(LearningUnitYear.objects.filter(id=luy.id))
        data.extend(volume_information(luys[0]))
    if optional_data_needed['has_teacher_list']:
        attribution_values = attribution_charge_new.find_attribution_charge_new_by_learning_unit_year_as_dict(
            luy).values()
        data.append(";".join([
            _get_attribution_line(value.get('person'))
            for value in attribution_values
        ]))
        data.append(";".join(
            [value.get('person').email for value in attribution_values]))
    if optional_data_needed['has_proposition']:
        proposal = find_by_learning_unit_year(luy)
        if proposal:
            data.append(proposal.get_type_display())
            data.append(proposal.get_state_display())
        else:
            data.append('')
            data.append('')
    if optional_data_needed['has_english_title']:
        data.append(luy.complete_title_english)
    if optional_data_needed['has_language']:
        data.append(luy.language)
    if optional_data_needed['has_specifications']:
        specifications_data = _build_specifications_cols(luy, gey)
        for k, v in zip(specifications_data._fields, specifications_data):
            data.append(v)
    if optional_data_needed['has_description_fiche']:
        description_fiche = _build_description_fiche_cols(luy, gey)
        for k, v in zip(description_fiche._fields, description_fiche):
            data.append(v)
    return data
Ejemplo n.º 48
0
def _fix_data(gey: GroupElementYear, luy: LearningUnitYear):
    data = []
    data_fix = FixLineUEContained(acronym=luy.acronym,
                                  year=luy.academic_year,
                                  title=luy.complete_title_i18n,
                                  type=luy.get_container_type_display(),
                                  subtype=luy.get_subtype_display(),
                                  gathering="{} - {}".format(
                                      gey.parent.partial_acronym,
                                      gey.parent.title),
                                  block=gey.block or '',
                                  mandatory=str.strip(yesno(gey.is_mandatory)))
    for name in data_fix._fields:
        data.append(getattr(data_fix, name))
    return data
Ejemplo n.º 49
0
 def build_row(self, obj, fields):
     row = []
     for f in fields:
         value = getattr(obj, f)
         try:
             row.append(value.strftime('%m/%d/%Y'))
         except AttributeError:
             if isinstance(value, bool):
                 value = yesno(value, _("yes,no"))
             if f == 'title':
                 value = _(obj.title)
             if f == 'confirmed_on':
                 value = '01/01/1970'
             row.append(value)
     return row
Ejemplo n.º 50
0
def friendly(value): 
    if type(value) is QuerySet:
        qs = value
        value = []        
        for object in qs:
            value.append(object.__unicode__())
    if type(value) is list:
        value = ", ".join(value)
    if type(value) is bool:
        value = yesno(value, u"%s,%s" % (_('yes'), _('no')),)
    if hasattr(value, 'url'):
        value = value.url
    if not isinstance(value, basestring):
        value = unicode(value)
    return value
Ejemplo n.º 51
0
 def build_row(self, obj, fields):
     row = []
     for f in fields:
         value = getattr(obj, f)
         try:
             row.append(value.strftime("%m/%d/%Y"))
         except AttributeError:
             if isinstance(value, bool):
                 value = yesno(value, _("yes,no"))
             if f == "title":
                 value = _(obj.title)
             if f == "confirmed_on":
                 value = "01/01/1970"
             row.append(value)
     return row
Ejemplo n.º 52
0
def export_invitees_as_csv(request):
    rows = [["Invite Email", "Name", "Is attending?", "Special requirements"]]
    for invitee in Invitee.objects.select_related("invitee"):
        row = [
            invitee.invite.email.encode("utf8"),
            invitee.name.encode("utf8"),
            yesno(invitee.is_attending).encode("utf8"),
            unicode(invitee.special_requirements).encode("utf8"),
            ]
        rows.append(row)
    
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = "attachment; filename=invitees.csv"
    csv_writer = csv.writer(response)
    csv_writer.writerows(rows)
    return response
Ejemplo n.º 53
0
def friendly(value):
    """
    Returns a more "human-friendly" representation of value than repr()
    """
    if isinstance(value, QuerySet):
        qs = value
        value = []
        for object in qs:
            value.append(object.__unicode__())
    if isinstance(value, list):
        value = ', '.join(value)
    if isinstance(value, bool):
        value = yesno(value, u'%s,%s' % (_('yes'), _('no')),)
    if not isinstance(value, basestring):
        value = unicode(value)
    return value
Ejemplo n.º 54
0
    def get_display_value(self, context, object):
        display_callable = maybe_callable(self.display, context=context)
        if display_callable:
            return display_callable(object)
        value = object
        for bit in self.display.split("__"):
            value = getattr(value, bit, None)

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())

        if not value:
            value = ""

        return force_text(value)
Ejemplo n.º 55
0
def friendly(value, null_value=None, return_markup=True):
    if value is None and not (null_value is None):
        return null_value
    if type(value) is QuerySet:
        qs = value
        value = []        
        for object in qs:
            value.append(object.__unicode__())
    if type(value) is list:
        value = ", ".join(value)
    if type(value) is bool:
        value = yesno(value, u"%s,%s" % (_('yes'), _('no')),)
    if hasattr(value, 'url'):
        if return_markup:
            value = '<a href="%s" target="_blank">%s</a>' % (value.url, value.url,)
        else:
            value = value.url
    if not isinstance(value, basestring):
        value = unicode(value)
    return value
Ejemplo n.º 56
0
    def check_different_types(self, value):
        if isinstance(value, ProductMedia):
            return "<img src='/media/%s'>" % value.get_thumbnail()

        if isinstance(value, Image):
            thumbnailer = get_thumbnailer(value)
            options = {"size": (64, 64)}
            thumbnail = thumbnailer.get_thumbnail(options, generate=True)
            return "<img src='%s'>" % thumbnail.url

        if isinstance(value, bool):
            value = yesno(value)

        if isinstance(value, Manager):
            value = ", ".join("%s" % x for x in value.all())
            return value

        if isinstance(value, datetime.datetime):
            return get_locally_formatted_datetime(value)

        if isinstance(value, Money):
            return escape(format_money(value))
Ejemplo n.º 57
0
    def formatted_value(self):
        """
        Get a human-consumable value for the attribute.

        The current locale is used for formatting.

        :return: Textual value
        :rtype: str
        """
        try:
            if self.attribute.type == AttributeType.BOOLEAN:
                return yesno(self.value)
            if self.attribute.type in (AttributeType.INTEGER, AttributeType.DECIMAL):
                return format_number(self.value)
            if self.attribute.type == AttributeType.TIMEDELTA:
                a = now()
                b = a + self.value
                return timesince(a, b)
            if self.attribute.type in (AttributeType.DATETIME, AttributeType.DATE):
                return format_datetime(self.value)
        except:  # If formatting fails, fall back to string formatting.
            pass
        return six.text_type(self.value)
Ejemplo n.º 58
0
        def _format_row(row):
            if "doc" in row:
                case = CommCareCase.wrap(row["doc"])
            elif "id" in row:
                case = CommCareCase.get(row["id"])
            else:
                raise ValueError("Can't construct case object from row result %s" % row)

            if case.domain != self.domain:
                logging.error("case.domain != self.domain; %r and %r, respectively" % (case.domain, self.domain))

            assert(case.domain == self.domain)

            owner_id = case.owner_id if case.owner_id else case.user_id
            owning_group = None
            try:
                owning_group = Group.get(owner_id)
            except Exception:
                pass

            user_id = self.individual if self.individual else owner_id
            case_owner = self.usernames.get(user_id, "Unknown [%s]" % user_id)

            if owning_group and owning_group.name:
                if self.individual:
                    case_owner = '%s <span class="label label-inverse">%s</span>' % (case_owner, owning_group.name)
                else:
                    case_owner = '%s <span class="label label-inverse">Group</span>' % owning_group.name


            return ([] if self.case_type else [case.type]) + [
                self.case_data_link(row['id'], case.name),
                case_owner,
                self.date_to_json(case.opened_on),
                self.date_to_json(case.modified_on),
                yesno(case.closed, "closed,open")
            ]
Ejemplo n.º 59
0
def field_value(revision, field):
    value = getattr(revision, field)
    if field in ['is_surrogate', 'no_volume', 'display_volume_with_number',
                 'no_brand', 'page_count_uncertain', 'title_inferred',
                 'no_barcode', 'no_indicia_frequency', 'no_isbn',
                 'year_began_uncertain', 'year_ended_uncertain',
                 'on_sale_date_uncertain', 'is_comics_publication']:
        return yesno(value, 'Yes,No')
    elif field in ['is_current']:
        res_holder_display = ''
        if revision.previous():
            reservation = revision.source.get_ongoing_reservation()
            if revision.previous().is_current and not value and reservation:
                res_holder = reservation.indexer
                res_holder_display = ' (ongoing reservation held by %s %s)' % \
                  (res_holder.first_name, res_holder.last_name)
        return yesno(value, 'Yes,No') + res_holder_display
    elif field in ['publisher', 'indicia_publisher', 'series',
                   'origin_issue', 'target_issue']:
        return absolute_url(value)
    elif field in ['origin', 'target']:
        return value.full_name_with_link()
    elif field == 'brand':
        if value and value.emblem:
            return mark_safe('<img src="' + value.emblem.icon.url + '"> ' \
                             + absolute_url(value))
        return absolute_url(value)
    elif field in ['notes', 'tracking_notes', 'publication_notes',
                   'characters', 'synopsis']:
        return linebreaksbr(value)
    elif field == 'reprint_notes':
        reprint = ''
        if value.strip() != '':
            for string in split_reprint_string(value):
                string = string.strip()
                reprint += '<li> ' + esc(string) + ' </li>'
            if reprint != '':
                reprint = '<ul>' + reprint + '</ul>'
        return mark_safe(reprint)
    elif field in ['url']:
        return urlize(value)
    elif field in ['indicia_pub_not_printed']:
        return yesno(value, 'Not Printed,Printed')
    elif field == 'group':
        brand_groups = ''
        for brand in value.all():
            brand_groups += absolute_url(brand) + '; '
        if brand_groups:
            brand_groups = brand_groups[:-2]
        return mark_safe(brand_groups)
    elif field in ['no_editing', 'no_script', 'no_pencils', 'no_inks',
                   'no_colors', 'no_letters']:
        return yesno(value, 'X, ')
    elif field in ['page_count']:
        if revision.source_name == 'issue' and \
           revision.changeset.storyrevisions.count():
            # only calculate total sum for issue not sequences
            total_pages = sum_page_counts(revision.active_stories())
            if revision.variant_of:
                if revision.changeset.issuerevisions.count() > 1:
                    stories = revision.changeset.storyrevisions\
                                      .exclude(issue=revision.issue)
                else:
                    stories = revision.variant_of.active_stories()
                if revision.active_stories().count():
                    # variant has cover sequence, add page counts without cover
                    stories = stories.exclude(sequence_number=0)
                    total_pages += sum_page_counts(stories)
                else:
                    # variant has no extra cover sequence
                    total_pages = sum_page_counts(stories)
            sum_story_pages = format_page_count(total_pages)

            return u'%s (note: total sum of story page counts is %s)' % \
                   (format_page_count(value), sum_story_pages)
        return format_page_count(value)
    elif field == 'isbn':
        if value:
            if validated_isbn(value):
                return u'%s (note: valid ISBN)' % value
            elif len(value.split(';')) > 1:
                return_val = value + ' (note: '
                for isbn in value.split(';'):
                    return_val = return_val + u'%s; ' % ("valid ISBN" \
                                   if validated_isbn(isbn) else "invalid ISBN")
                return return_val + 'ISBNs are inequal)'
            elif value:
                return u'%s (note: invalid ISBN)' % value
    elif field == 'barcode':
        if value:
            barcodes = value.split(';')
            return_val = value + ' (note: '
            for barcode in barcodes:
                return_val = return_val + u'%s; ' % ("valid UPC/EAN" \
                             if valid_barcode(barcode) \
                             else "invalid UPC/EAN or non-standard")
            return return_val[:-2] + ')'
    elif field == 'leading_article':
        if value == True:
            return u'Yes (sorted as: %s)' % remove_leading_article(revision.name)
        else:
            return u'No'
    elif field in ['has_barcode', 'has_isbn', 'has_issue_title',
                   'has_indicia_frequency', 'has_volume', 'has_rating']:
        if hasattr(revision, 'changed'):
            if revision.changed[field] and value == False:
                kwargs = {field[4:]: ''}
                if field[4:] == 'issue_title':
                    kwargs = {'title': ''}
                if revision.series:
                    value_count = revision.series.active_issues()\
                                                 .exclude(**kwargs).count()
                    if value_count:
                        return 'No (note: %d issues have a non-empty %s value)' % \
                                (value_count, field[4:])
        return yesno(value, 'Yes,No')
    elif field == 'is_singleton':
        if hasattr(revision, 'changed'):
            if revision.changed[field] and value == True:
                 if revision.series:
                     value_count = revision.series.active_base_issues().count()
                     if value_count:
                        return 'Yes (note: the series has %d issue%s)' % \
                                (value_count, pluralize(value_count))
        return yesno(value, 'Yes,No')
    elif field == 'after' and not hasattr(revision, 'changed'):
        # for previous revision (no attr changed) display empty string
        return ''
    return value