Python django.contrib.humanize.templatetags.humanize.intcomma() Examples

The following are 19 code examples of django.contrib.humanize.templatetags.humanize.intcomma(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.humanize.templatetags.humanize , or try the search function .
Example #1
Source File: views.py    From explorer with Apache License 2.0 6 votes vote down vote up
def add_metadata(request, coin_symbol):
    block_hash = get_latest_block_hash(coin_symbol)

    block_overview = get_block_overview(
            block_representation=block_hash,
            coin_symbol=coin_symbol,
            txn_limit=500,
            api_key=BLOCKCYPHER_API_KEY,
            )

    random_tx_hash = choice(block_overview['txids'])

    redir_url = reverse(
            'add_metadata_to_tx',
            kwargs={'coin_symbol': coin_symbol, 'tx_hash': random_tx_hash},
            )

    msg = _('%(cs_display)s transaction %(tx_hash)s from latest block (%(latest_block_num)s) randomly selected' % {
        'cs_display': COIN_SYMBOL_MAPPINGS[coin_symbol]['currency_abbrev'],
        'tx_hash': random_tx_hash,
        'latest_block_num': intcomma(block_overview['height']),
        })

    messages.success(request, msg, extra_tags='safe')
    return HttpResponseRedirect(redir_url) 
Example #2
Source File: views.py    From govready-q with GNU General Public License v3.0 6 votes vote down vote up
def shared_static_pages(request, page):
    from django.utils.module_loading import import_string
    from django.contrib.humanize.templatetags.humanize import intcomma
    password_hasher = import_string(settings.PASSWORD_HASHERS[0])()
    password_hash_method = password_hasher.algorithm.upper().replace("_", " ") \
        + " (" + intcomma(password_hasher.iterations) + " iterations)"

    return render(request,
        page + ".html", {
        "base_template": "base.html",
        "SITE_ROOT_URL": request.build_absolute_uri("/"),
        "password_hash_method": password_hash_method,
        # "project_form": ProjectForm(request.user),
        "project_form": None,
    })

# SINGLE SIGN ON 
Example #3
Source File: copy_from.py    From django-postgres-copy with MIT License 5 votes vote down vote up
def save(self, silent=False, stream=sys.stdout):
        """
        Saves the contents of the CSV file to the database.

        Override this method and use 'self.create(cursor)`,
        `self.copy(cursor)`, `self.insert(cursor)`, and `self.drop(cursor)`
        if you need functionality other than the default create/copy/insert/drop
        workflow.

         silent:
           By default, non-fatal error notifications are printed to stdout,
           but this keyword may be set to disable these notifications.

         stream:
           Status information will be written to this file handle. Defaults to
           using `sys.stdout`, but any object with a `write` method is
           supported.
        """
        logger.debug("Loading CSV to {}".format(self.model.__name__))
        if not silent:
            stream.write("Loading CSV to {}\n".format(self.model.__name__))

        # Connect to the database
        with self.conn.cursor() as c:
            self.create(c)
            self.copy(c)
            insert_count = self.insert(c)
            self.drop(c)

        if not silent:
            stream.write("{} records loaded\n".format(intcomma(insert_count)))

        return insert_count 
Example #4
Source File: formatting.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def to_int_comma(num):
    return intcomma(int(num)) 
Example #5
Source File: utils.py    From jorvik with GNU General Public License v3.0 5 votes vote down vote up
def testo_euro(numero, simbolo_html=False):
    euro = round(float(numero), 2)
    simbolo = "€" if simbolo_html else "€"
    return ("%s%s %s" % (intcomma(int(euro)), ("%0.2f" % euro)[-3:], simbolo)).replace('.', ',') 
Example #6
Source File: test_measures.py    From openprescribing with MIT License 5 votes vote down vote up
def _humanize(cost_saving):
    return intcomma(int(round(abs(cost_saving)))) 
Example #7
Source File: template_extras.py    From openprescribing with MIT License 5 votes vote down vote up
def roundpound(num):
    order = 10 ** math.floor(math.log10(num))
    if order > 0:
        return intcomma(int(round(num / order) * order))
    else:
        return str(int(round(num))) 
Example #8
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        search_term = self.request.GET.get('query')
        submission_values = self.object_list.value()
        count_values = submission_values.get('value__count')
        total_value = intcomma(submission_values.get('value__sum'))
        average_value = intcomma(round(submission_values.get('value__avg')))

        return super().get_context_data(
            search_term=search_term,
            filter_action=self.filter_action,
            count_values=count_values,
            total_value=total_value,
            average_value=average_value,
            **kwargs,
        ) 
Example #9
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        submissions = ApplicationSubmission.objects.all()
        submission_undetermined_count = submissions.undetermined().count()
        review_my_count = submissions.reviewed_by(self.request.user).count()

        submission_value = submissions.current().value()
        submission_sum = intcomma(submission_value.get('value__sum'))
        submission_count = submission_value.get('value__count')

        submission_accepted_value = submissions.current_accepted().value()
        submission_accepted_sum = intcomma(submission_accepted_value.get('value__sum'))
        submission_accepted_count = submission_accepted_value.get('value__count')

        reviews = Review.objects.all()
        review_count = reviews.count()
        review_my_score = reviews.by_user(self.request.user).score()

        return super().get_context_data(
            submission_undetermined_count=submission_undetermined_count,
            review_my_count=review_my_count,
            submission_sum=submission_sum,
            submission_count=submission_count,
            submission_accepted_count=submission_accepted_count,
            submission_accepted_sum=submission_accepted_sum,
            review_count=review_count,
            review_my_score=review_my_score,
            **kwargs,
        ) 
Example #10
Source File: tables.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_fund_allocation(self, record):
        return f'${intcomma(record.amount_paid)} / ${intcomma(record.value)}' 
Example #11
Source File: ui_extras.py    From sfm-ui with MIT License 5 votes vote down vote up
def join_stats(d, status, sep=", "):
    joined = ""

    empty_extras = ""
    if status == Harvest.RUNNING:
        empty_extras = "Nothing yet"
    elif status == Harvest.REQUESTED:
        empty_extras = "Waiting for update"

    if d:
        for i, (item, count) in enumerate(d.items()):
            if i > 1:
                joined += sep
            joined += "{} {}".format(intcomma(count), item)
    return joined if joined else empty_extras 
Example #12
Source File: __init__.py    From edx-analytics-dashboard with GNU Affero General Public License v3.0 5 votes vote down vote up
def format_tip_percent(self, value):
        if value is None:
            formatted_percent = u'0'
        else:
            formatted_percent = intcomma(round(value, 3) * 100)

        return formatted_percent 
Example #13
Source File: enrollment.py    From edx-analytics-dashboard with GNU Affero General Public License v3.0 5 votes vote down vote up
def format_percentage(self, value):
        if value is None:
            formatted_percent = u'0'
        else:
            formatted_percent = intcomma(round(value, 3) * 100)

        return formatted_percent 
Example #14
Source File: estimator.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def format_currency(self, dollars):
        """ Provides a cost estimate in formatted dollars """
        dollars = round(float(dollars), 2)
        return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:]) 
Example #15
Source File: field_types.py    From intake with MIT License 5 votes vote down vote up
def get_display_value(self):
        """should return $100.00
        """
        value = self.get_current_value()
        if value is None:
            return ''
        return "${}.00".format(intcomma(value)) 
Example #16
Source File: metrics.py    From prospector with GNU General Public License v3.0 5 votes vote down vote up
def format_score(value):
    if value is None:
        return "N/A"

    if isinstance(value, bool):
        return '\u2714' if value else '\u2718'

    elif isinstance(value, int):
        return intcomma(value)

    f = floatformat(value, 2)
    if f:
        return f

    return value 
Example #17
Source File: forms.py    From django-polaris with Apache License 2.0 5 votes vote down vote up
def clean_amount(self):
        """Validate the provided amount of an asset."""
        amount = round(self.cleaned_data["amount"], self.decimal_places)
        if amount < self.min_amount:
            raise forms.ValidationError(
                _("The minimum amount is: %s")
                % intcomma(round(self.min_amount, self.decimal_places))
            )
        elif amount > self.max_amount:
            raise forms.ValidationError(
                _("The maximum amount is: %s")
                % intcomma(round(self.max_amount, self.decimal_places))
            )
        return amount 
Example #18
Source File: views.py    From coldfront with GNU General Public License v3.0 4 votes vote down vote up
def center_summary(request):
    context = {}

    # Publications Card
    publications_by_year = list(Publication.objects.filter(year__gte=1999).values(
        'unique_id', 'year').distinct().values('year').annotate(num_pub=Count('year')).order_by('-year'))

    publications_by_year = [(ele['year'], ele['num_pub'])
                            for ele in publications_by_year]

    publication_by_year_bar_chart_data = generate_publication_by_year_chart_data(
        publications_by_year)
    context['publication_by_year_bar_chart_data'] = publication_by_year_bar_chart_data
    context['total_publications_count'] = Publication.objects.filter(
        year__gte=1999).values('unique_id', 'year').distinct().count()

    # Research Outputs card
    context['total_research_outputs_count'] = ResearchOutput.objects.all().distinct().count()

    # Grants Card
    total_grants_by_agency_sum = list(Grant.objects.values(
        'funding_agency__name').annotate(total_amount=Sum('total_amount_awarded')))

    total_grants_by_agency_count = list(Grant.objects.values(
        'funding_agency__name').annotate(count=Count('total_amount_awarded')))

    total_grants_by_agency_count = {
        ele['funding_agency__name']: ele['count'] for ele in total_grants_by_agency_count}

    total_grants_by_agency = [['{}: ${} ({})'.format(
        ele['funding_agency__name'],
        intcomma(int(ele['total_amount'])),
        total_grants_by_agency_count[ele['funding_agency__name']]
    ), ele['total_amount']] for ele in total_grants_by_agency_sum]

    total_grants_by_agency = sorted(
        total_grants_by_agency, key=operator.itemgetter(1), reverse=True)
    grants_agency_chart_data = generate_total_grants_by_agency_chart_data(
        total_grants_by_agency)
    context['grants_agency_chart_data'] = grants_agency_chart_data
    context['grants_total'] = intcomma(
        int(sum(list(Grant.objects.values_list('total_amount_awarded', flat=True)))))
    context['grants_total_pi_only'] = intcomma(
        int(sum(list(Grant.objects.filter(role='PI').values_list('total_amount_awarded', flat=True)))))
    context['grants_total_copi_only'] = intcomma(
        int(sum(list(Grant.objects.filter(role='CoPI').values_list('total_amount_awarded', flat=True)))))
    context['grants_total_sp_only'] = intcomma(
        int(sum(list(Grant.objects.filter(role='SP').values_list('total_amount_awarded', flat=True)))))

    return render(request, 'portal/center_summary.html', context) 
Example #19
Source File: forms.py    From django-polaris with Apache License 2.0 4 votes vote down vote up
def __init__(self, transaction: Transaction, *args, **kwargs):
        # For testing via anchor-validator.herokuapp.com
        test_value = kwargs.pop("test_value", None)
        if not test_value:
            test_value = (
                "103" if transaction.kind == Transaction.KIND.deposit else "100"
            )

        super().__init__(*args, **kwargs)

        self.transaction = transaction
        self.asset = transaction.asset
        self.decimal_places = self.asset.significant_decimals
        if transaction.kind == Transaction.KIND.deposit:
            self.min_amount = round(self.asset.deposit_min_amount, self.decimal_places)
            self.max_amount = round(self.asset.deposit_max_amount, self.decimal_places)
            self.min_default = Asset._meta.get_field("deposit_min_amount").default
            self.max_default = Asset._meta.get_field("deposit_max_amount").default
        else:
            self.min_amount = round(
                self.asset.withdrawal_min_amount, self.decimal_places
            )
            self.max_amount = round(
                self.asset.withdrawal_max_amount, self.decimal_places
            )
            self.min_default = Asset._meta.get_field("withdrawal_min_amount").default
            self.max_default = Asset._meta.get_field("withdrawal_max_amount").default

        # Re-initialize the 'amount' field now that we have all the parameters necessary
        self.fields["amount"].__init__(
            widget=forms.NumberInput(
                attrs={
                    "class": "input",
                    "inputmode": "decimal",
                    "symbol": self.asset.symbol,
                    "test-value": test_value,
                }
            ),
            min_value=self.min_amount,
            max_value=self.max_amount,
            decimal_places=self.decimal_places,
            label=_("Amount"),
            localize=True,
        )

        limit_str = ""
        if self.min_amount > self.min_default and self.max_amount < self.max_default:
            limit_str = f"({intcomma(self.min_amount)} - {intcomma(self.max_amount)})"
        elif self.min_amount > self.min_default:
            limit_str = _("(minimum: %s)") % intcomma(self.min_amount)
        elif self.max_amount < self.max_default:
            limit_str = _("(maximum: %s)") % intcomma(self.max_amount)

        if limit_str:
            self.fields["amount"].label += " " + limit_str