Python django.template.defaultfilters.pluralize() Examples

The following are 15 code examples of django.template.defaultfilters.pluralize(). 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.template.defaultfilters , or try the search function .
Example #1
Source File: wagtailstreamforms_hooks.py    From wagtailstreamforms with MIT License 6 votes vote down vote up
def save_form_submission_data(instance, form):
    """ saves the form submission data """

    # copy the cleaned_data so we dont mess with the original
    submission_data = form.cleaned_data.copy()

    # change the submission data to a count of the files
    for field in form.files.keys():
        count = len(form.files.getlist(field))
        submission_data[field] = "{} file{}".format(count, pluralize(count))

    # save the submission data
    submission = instance.get_submission_class().objects.create(
        form_data=json.dumps(submission_data, cls=FormSubmissionSerializer),
        form=instance,
    )

    # save the form files
    for field in form.files:
        for file in form.files.getlist(field):
            FormSubmissionFile.objects.create(
                submission=submission, field=field, file=file
            ) 
Example #2
Source File: remove_duplicate_conditions.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        duplicate_records = self.get_duplicate_records()
        duplicate_count = duplicate_records.count()
        logging.info('%d duplicate condition%s found in database.', duplicate_count, pluralize(duplicate_count))

        for record in duplicate_records:
            num_of_duplicates = record.pop('id_count')
            conditions = Condition.objects.filter(**record)
            first_condition = conditions.first()
            logging.info('Condition with id [%d] has %d duplicates.', first_condition.id, int(num_of_duplicates) - 1)
            for condition in conditions.exclude(id=first_condition.id):
                conditional_offers_queryset = ConditionalOffer.objects.filter(condition=condition)
                if conditional_offers_queryset.exists():
                    conditional_offers_queryset.update(condition=first_condition)
                logging.info('Deleting condition record with id [%d].', condition.id)
                condition.delete() 
Example #3
Source File: wagtail_hooks.py    From wagtail-personalisation with MIT License 5 votes vote down vote up
def render(self):
        page_count = models.PersonalisablePageMetadata.objects.filter(segment__isnull=True).count()
        title = _("Personalised Page")
        return mark_safe("""
            <li class="icon icon-fa-file-o">
                <span>{}</span>{}{}
            </li>""".format(page_count, title, pluralize(page_count))) 
Example #4
Source File: wagtail_hooks.py    From wagtail-personalisation with MIT License 5 votes vote down vote up
def render(self):
        page_count = models.PersonalisablePageMetadata.objects.filter(
            segment__isnull=False).count()
        title = _("Variant")
        return mark_safe("""
                <li class="icon icon-fa-files-o">
                    <span>{}</span>{}{}
                </li>""".format(page_count, title, pluralize(page_count))) 
Example #5
Source File: __init__.py    From zulip with Apache License 2.0 5 votes vote down vote up
def environment(**options: Any) -> Environment:
    env = Environment(**options)
    env.globals.update({
        'default_page_params': {
            'debug_mode': False,
            'webpack_public_path': staticfiles_storage.url(
                settings.WEBPACK_LOADER['DEFAULT']['BUNDLE_DIR_NAME'],
            ),
        },
        'static': staticfiles_storage.url,
        'url': reverse,
        'render_markdown_path': render_markdown_path,
    })

    env.install_gettext_translations(translation, True)

    env.filters['slugify'] = slugify
    env.filters['pluralize'] = pluralize
    env.filters['display_list'] = display_list
    env.filters['device_action'] = device_action
    env.filters['timesince'] = timesince

    return env 
Example #6
Source File: wagtailstreamforms_hooks.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def email_submission(instance, form):
    """ Send an email with the submission. """

    if not hasattr(instance, 'advanced_settings'):
        return

    addresses = [instance.advanced_settings.to_address]
    content = ['Please see below submission\n', ]
    from_address = settings.DEFAULT_FROM_EMAIL
    subject = 'New Form Submission : %s' % instance.title

    # build up the email content
    for field, value in form.cleaned_data.items():
        if field in form.files:
            count = len(form.files.getlist(field))
            value = '{} file{}'.format(count, pluralize(count))
        elif isinstance(value, list):
            value = ', '.join(value)
        content.append('{}: {}'.format(field, value))
    content = '\n'.join(content)

    # create the email message
    email = EmailMessage(
        subject=subject,
        body=content,
        from_email=from_address,
        to=addresses
    )

    # attach any files submitted
    for field in form.files:
        for file in form.files.getlist(field):
            file.seek(0)
            email.attach(file.name, file.read(), file.content_type)

    # finally send the email
    email.send(fail_silently=True) 
Example #7
Source File: change_priority_of_offers.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        limit = options['limit']
        offset = options['offset']
        priority = options['priority']

        try:
            conditional_offers = ConditionalOffer.objects.filter(
                offer_type=ConditionalOffer.VOUCHER,
                priority=priority
            )[offset:offset + limit]

            count = len(conditional_offers)
            if count == 0:
                logger.info('No offer found which needs a priority fix')
                return

            line_feed = '\n'
            offer_names = 'Conditional offers to be updated{line_feed}'.format(line_feed=line_feed)
            for i in range(count):
                if i == count - 1:
                    line_feed = ''
                offer_names = '{names}{index}. {name}{line_feed}'.format(
                    names=offer_names, index=i + 1, name=conditional_offers[i].name, line_feed=line_feed
                )

            # List down all conditional which needs to be updated.
            logger.warning(offer_names)

            pluralized = pluralize(count)
            if query_yes_no(self.CONFIRMATION_PROMPT.format(count=count, pluralized=pluralized), default="no"):
                for offer in conditional_offers:
                    offer.priority = OFFER_PRIORITY_VOUCHER
                    offer.save()
                logger.info('Operation completed. %d conditional offer%s updated successfully.', count, pluralized)
            else:
                logger.info('Operation canceled.')

        except Exception as exc:  # pylint: disable=broad-except
            logger.exception('Command execution failed while executing batch %d,%d\n%s', offset, limit, exc) 
Example #8
Source File: test_pluralize.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_integers(self):
        self.assertEqual(pluralize(1), '')
        self.assertEqual(pluralize(0), 's')
        self.assertEqual(pluralize(2), 's') 
Example #9
Source File: test_pluralize.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_floats(self):
        self.assertEqual(pluralize(0.5), 's')
        self.assertEqual(pluralize(1.5), 's') 
Example #10
Source File: test_pluralize.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_decimals(self):
        self.assertEqual(pluralize(Decimal(1)), '')
        self.assertEqual(pluralize(Decimal(0)), 's')
        self.assertEqual(pluralize(Decimal(2)), 's') 
Example #11
Source File: test_pluralize.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_lists(self):
        self.assertEqual(pluralize([1]), '')
        self.assertEqual(pluralize([]), 's')
        self.assertEqual(pluralize([1, 2, 3]), 's') 
Example #12
Source File: test_pluralize.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_suffixes(self):
        self.assertEqual(pluralize(1, 'es'), '')
        self.assertEqual(pluralize(0, 'es'), 'es')
        self.assertEqual(pluralize(2, 'es'), 'es')
        self.assertEqual(pluralize(1, 'y,ies'), 'y')
        self.assertEqual(pluralize(0, 'y,ies'), 'ies')
        self.assertEqual(pluralize(2, 'y,ies'), 'ies')
        self.assertEqual(pluralize(0, 'y,ies,error'), '') 
Example #13
Source File: test_pluralize.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_value_error(self):
        self.assertEqual(pluralize('', 'y,es'), 'y') 
Example #14
Source File: update_addon_urls.py    From normandy with Mozilla Public License 2.0 4 votes vote down vote up
def handle(self, *args, **options):
        extension_by_filename = {}
        for extension in Extension.objects.all():
            filename = get_filename_from_url(extension.xpi.url)
            extension_by_filename[filename] = extension

        target_revisions = RecipeRevision.objects.filter(action__name="opt-out-study")
        update_count = 0
        for rev in target_revisions:
            # Pull into a local variable to modify the arguments since
            # `rev.arguments` is actually a property that parses JSON, not a
            # real attribute of the object
            arguments = rev.arguments

            if not arguments.get("addonUrl"):
                self.stderr.write(
                    f"Warning: Recipe {rev.recipe.id} revision {rev.id} has action=opt-out-study, "
                    f"but no addonUrl"
                )
                continue

            filename = get_filename_from_url(arguments["addonUrl"])

            if filename not in extension_by_filename:
                self.stderr.write(
                    f"Warning: Recipe {rev.recipe.id} revision {rev.id} has an addonUrl that does "
                    f"not match any in the database."
                )
                continue

            extension = extension_by_filename[filename]
            new_url = extension.xpi.url
            if arguments["addonUrl"] == new_url:
                # nothing to do
                continue

            arguments["addonUrl"] = extension.xpi.url
            rev.arguments = arguments
            rev.save()

            # The revision has changed so update the signature
            recipe = rev.recipe
            recipe.update_signature()
            recipe.save()

            update_count += 1

        self.stdout.write(f"{update_count} revision{pluralize(update_count)} updated") 
Example #15
Source File: remove_partner_offers.py    From ecommerce with GNU Affero General Public License v3.0 4 votes vote down vote up
def handle(self, *args, **options):
        partner_code = options['partner']

        catalogs = Catalog.objects.filter(partner__short_code__iexact=partner_code)
        ranges = Range.objects.filter(catalog__in=catalogs).distinct()
        benefits = Benefit.objects.filter(range__in=ranges).distinct()
        conditional_offers = ConditionalOffer.objects.filter(benefit__in=benefits).distinct()

        count = len(conditional_offers)
        if count == 0:
            logger.info('No offer found for partner [%s].', partner_code)
            return

        line_feed = '\n'
        offer_names = 'Conditional offers to be deleted for partner [{partner_code}] {line_feed}'.format(
            partner_code=partner_code, line_feed=line_feed
        )
        for i in range(count):
            if i == count - 1:
                line_feed = ''
            offer_names = '{names} {index}. {name} {line_feed}'.format(
                names=offer_names, index=i + 1, name=conditional_offers[i].name, line_feed=line_feed
            )

        # List down all conditional offers to be deleted.
        logger.warning(offer_names)

        pluralized = pluralize(count)
        if query_yes_no(self.CONFIRMATION_PROMPT.format(count=count, pluralized=pluralized), default="no"):
            # disconnect post_delete oscar receiver to avoid Condition matching query does not exist.
            signals.post_delete.disconnect(
                receiver=delete_unused_related_conditions_and_benefits, sender=ConditionalOffer
            )

            # delete partner related conditional offers.
            conditional_offers.delete()

            # re-connect post_delete oscar receiver.
            signals.post_delete.connect(
                receiver=delete_unused_related_conditions_and_benefits, sender=ConditionalOffer
            )
            logger.info('%d conditional offer%s removed successfully.', count, pluralized)
        else:
            logger.info('Operation canceled.')
            return