def get_help_text(self): return ngettext_lazy( singular= "Your password must contain at most %(max_length)d character.", plural= "Your password must contain at most %(max_length)d characters.", number=self.max_length, ) % { 'max_length': self.max_length }
def my_context_processor(request): context = { 'my_variable': 'Hello world', 'users': User.objects.all() } if request.user.is_authenticated: context['auth'] = True count = int(request.GET.get('count', 0)) context['some_string'] = ngettext_lazy('%(count)s копейка', '%(count)s копейка', count) % {'count': count} return context
def create_table(ev, subjects): project_path = os.path.curdir build_path = os.path.join(project_path, '.build') out_filename = os.path.join(build_path, 'template') documentclass_name = 'article' options = [] options_latex = '\n'.join(r'\newcommand{\%s}{%s}' % pair for pair in options) options_latex = '' title = '' if len(subjects) > 0: title = str(subjects[0].event) seats = subjects[0].event.num_max_per_subject rows = StringIO() for i, sub in enumerate(subjects): row = list( map(tex_escape, [str(i + 1), sub.name, sub.given_name, sub.email])) row.extend([ sub.seats if ev.assigned_seats else str(sub.num_seats), '\\ding{51}' if sub.status_confirmed else '\\ding{55}', '' ]) rows.write('%s\\\\ \\hline \n' % ' & '.join(row)) header = '%s\\\\ \n' % ' & '.join( map(str, [ '', _('name'), _('given_name'), _('email'), ngettext_lazy('seat', 'seats', seats), _('confirmed'), _('present') ])) latex = LATEX_TEMPLATE.safe_substitute( options=options_latex, documentclass=documentclass_name, title=title, header=header, rows=rows.getvalue(), ) shutil.rmtree(build_path, ignore_errors=True) os.makedirs(build_path, exist_ok=True) with open(out_filename + '.tex', 'w') as out_file: out_file.write(latex) subprocess.run(['pdflatex', '-output-directory', build_path, out_filename]) # shutil.copy2(out_filename + '.pdf', os.path.dirname(in_filename)) return out_filename + '.pdf'
class UsernameMinLengthValidator(MinLengthValidator): message = ngettext_lazy( singular= 'Username must contain at least %(limit_value)d alphanumeric character (it has %(show_value)d).', plural= 'Username must contain at least %(limit_value)d alphanumeric characters (it has %(show_value)d).', number='limit_value', ) def clean(self, x): return len(normalize_username(username=x))
def get_min_max_length_errors(self): errors = [] if getattr(self, 'min_length', None): self.widget.attrs['ng-minlength'] = self.min_length if getattr(self, 'max_length', None): self.widget.attrs['ng-maxlength'] = self.max_length for item in self.validators: if getattr(item, 'code', None) == 'min_length': message = ngettext_lazy( 'Ensure this value has at least %(limit_value)d character', 'Ensure this value has at least %(limit_value)d characters', 'limit_value') errors.append(('$error.minlength', message % {'limit_value': self.min_length})) if getattr(item, 'code', None) == 'max_length': message = ngettext_lazy( 'Ensure this value has at most %(limit_value)d character', 'Ensure this value has at most %(limit_value)d characters', 'limit_value') errors.append(('$error.maxlength', message % {'limit_value': self.max_length})) return errors
def validate(self, password, user=None): if len(password) < self.min_length: raise ValidationError( ngettext_lazy( singular="This password is too short. It must contain at least %(min_length)d character.", plural="This password is too short. It must contain at least %(min_length)d characters.", number=self.min_length, ), code='password_too_short', params={'min_length': self.min_length}, )
def delete_url_key(self, request, queryset): team_speakers = [team.speaker_set.all() for team in queryset] for speakers in team_speakers: speakers.update(url_key=None) message = ngettext_lazy( "%(count)d speaker had their URL key removed.", "%(count)d speakers had their URL keys removed.", len(team_speakers)) % { 'count': len(team_speakers) } self.message_user(request, message)
class ImportAdjudicatorsNumbersForm(BaseNumberForEachInstitutionForm): num_detail_fields = len(AdjudicatorDetailsForm.base_fields) + 1 too_many_error_message = ngettext_lazy( "Sorry, you can only import up to %(max_allowed)d adjudicator at a time. " "(These numbers currently add to %(given)d.) " "Try splitting your import into smaller chunks.", "Sorry, you can only import up to %(max_allowed)d adjudicators at a time. " "(These numbers currently add to %(given)d.) " "Try splitting your import into smaller chunks.", 'max_allowed')
class SetNullHandler(LabelReplacingHandler): empty_message = _('OK: no instance of «{model}» have to be updated.') instances_message = ngettext_lazy( 'BEWARE: {count} instance of «{model}» uses «{instance}» & ' 'will be updated (the field will be emptied).', 'BEWARE: {count} instances of «{model}» use «{instance}» & ' 'will be updated (the field will be emptied).', ) def get_form_field(self): return None if self.field_is_hidden else super().get_form_field()
def get_assignation_final_status(self, contestant, **kwargs): count = contestant.corrections.filter( event_type=self.event_type.value).count() corrections = ngettext_lazy("%(count)d correction", "%(count)d corrections", count) % { 'count': count } return format_html( '{} <small class="text-muted"> - {}</small>', Assignation.label_for(Assignation(contestant.assignation_final)), corrections)
def validate(self, password, user=None): if len(password) > self.max_length: raise ValidationError( ngettext_lazy( singular="This password is too long. It must contain at most %(max_length)d character.", plural="This password is too long. It must contain at most %(max_length)d characters.", number=self.max_length, ), code='password_too_long', params={'max_length': self.max_length}, )
class SlugMaxLengthValidator(MaxLengthValidator): message = ngettext_lazy( singular= 'Username must contain at most %(limit_value)d character (it has %(show_value)d).', plural= 'Username must contain at most %(limit_value)d characters (it has %(show_value)d).', number='limit_value', ) def clean(self, x): return len(normalize_slug(slug=x))
def truncate_cell_contents( head_list: List[str], data_list: List[List[str]], max_length: int ) -> Tuple[Tuple[int, str], Tuple[List[str], List[List[str]]]]: num_objects = len(data_list) data_list = [[ str(cell) if len(str(cell)) <= max_length else str(cell)[:max_length] + "..." for cell in row ] for row in data_list] msg = ngettext_lazy("%d Result Found", "%d Results Found") % num_objects return (200, msg), (head_list, data_list)
class MaxLengthValidator(BaseValidator): message = ngettext_lazy( 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).', 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).', 'limit_value') code = 'max_length' def compare(self, a, b): return a > b def clean(self, x): return len(x)
def specific_columns( head_list: List[str], data_list: List[List[str]], head_names_list: List[str] ) -> Tuple[Tuple[int, str], Tuple[List[str], List[List[str]]]]: num_objects = len(data_list) selected_idx_list = [head_list.index(head) for head in head_names_list] selected_head_list = [head_list[i] for i in selected_idx_list] selected_data_list = [[row[i] for i in selected_idx_list] for row in data_list] msg = ngettext_lazy("%d Result Found", "%d Results Found") % num_objects return (200, msg), (selected_head_list, selected_data_list)
def resave_ballots(self, request, queryset): q = queryset.select_related('debate__round__tournament').order_by('tournament_id') count = q.count() for tournament, bss in groupby(q, lambda bs: bs.debate.round.tournament): populate_results(bss, tournament) for bs in bss: bs.result.save() self.message_user(request, ngettext_lazy( "Resaved results for %(count)d ballot submission.", "Resaved results for %(count)d ballot submissions.", count) % {'count': count})
def assign_emoji(self, request, queryset): count = queryset.update(emoji=None) for tournament, teams in groupby( queryset.select_related('tournament').order_by( 'tournament_id'), lambda t: t.tournament): set_emoji(list(teams), tournament) message = ngettext_lazy("%(count)d team had their emoji reset.", "%(count)d teams had their emojis reset.", count) % { 'count': count } self.message_user(request, message)
class MinLengthValidator(BaseValidator): message = ngettext_lazy( "Ensure this value has at least %(limit_value)d character (it has %(show_value)d).", "Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).", "limit_value", ) code = "min_length" def compare(self, a, b): return a < b def clean(self, x): return len(x)
def validate(self, password, user=None): if len(password) > self.max_length: raise ValidationError( ngettext_lazy( singular= "This password is too long. It must contain at most %(max_length)d character.", plural= "This password is too long. It must contain at most %(max_length)d characters.", number=self.max_length, ), code='password_too_long', params={'max_length': self.max_length}, )
def validate(self, password, user=None): if len(password) < self.min_length: raise ValidationError( ngettext_lazy( singular= "This password is too short. It must contain at least %(min_length)d character.", plural= "This password is too short. It must contain at least %(min_length)d characters.", number=self.min_length, ), code='password_too_short', params={'min_length': self.min_length}, )
class CascadeHandler(LabelReplacingHandler): empty_message = _('OK: no instance of «{model}» have to be deleted.') instances_message = ngettext_lazy( 'BEWARE: {count} instance of «{model}» will be deleted.', 'BEWARE: {count} instances of «{model}» will be deleted.', ) def get_form_field(self): return None if self.field_is_hidden and not self.count else super( ).get_form_field() def replacer(self, new_value): return None
def page(head_list: List[str], data_list: List[List[str]], page: int, num_per_page: int) -> \ Tuple[Tuple[int, str], Tuple[List[str], List[List[str]], int]]: num_objects = len(data_list) paginator = Paginator(data_list, num_per_page) num_pages = paginator.num_pages if page < 1 or page > num_pages: return (404, _("Page Out Of Range.")), (head_list, [], 1) p = paginator.page(page) page_data_list = p.object_list msg = ngettext_lazy("%d Result Found", "%d Results Found") % num_objects return (200, msg), (head_list, page_data_list, num_pages)
def check_min_num(num: int): if min_num is not None and num - 1 < min_num: subcats_str = ngettext_lazy('subcategory', 'subcategories', min_num) error_msg = _( 'Unable to remove "%(target_category)s" category from "%(parent_category)s": ' 'parent category requires at least %(num)s %(subcats_str)s.' ) % { 'target_category': category.title, 'parent_category': category_list.get_title(), 'num': min_num, 'subcats_str': subcats_str } raise SitecatsValidationError(error_msg)
def check_max_num(num: int, max_num: Optional[int], category_title: str): if max_num is not None and num + 1 > max_num: subcats_str = ngettext_lazy('subcategory', 'subcategories', max_num) error_msg = _( 'Unable to add "%(target_category)s" category into "%(parent_category)s": ' 'parent category can have at most %(num)s %(subcats_str)s.' ) % { 'target_category': category_title, 'parent_category': category_list.get_title(), 'num': max_num, 'subcats_str': subcats_str } raise SitecatsValidationError(error_msg)
class DashboardTable(Table): caption = ngettext_lazy('%d Row', '%d Rows') def get_caption_display(self): # Allow overriding the caption with an arbitrary string that we cannot # interpolate the number of rows in try: return self.caption % self.paginator.count except TypeError: pass return self.caption class Meta: template_name = 'oscar/dashboard/table.html' attrs = {'class': 'table table-striped table-bordered'}
class SetHandler(LabelReplacingHandler): empty_message = _('OK: no instance of «{model}» have to be updated.') instances_message = ngettext_lazy( 'BEWARE: {count} instance of «{model}» uses «{instance}» & ' 'will be updated (the field will be set to the fallback value).', 'BEWARE: {count} instances of «{model}» use «{instance}» & ' 'will be updated (the field will be set to the fallback value).', ) def get_form_field(self): return None if self.field_is_hidden else super().get_form_field() def replacer(self, new_value): return None if self.field_is_hidden else deletion.SETReplacer( model_field=self.field)
class BootstrapRowFormMixin(ManageChildrenFormMixin, EntangledModelFormMixin): """ Form class to add non-materialized field to count the number of children. """ ROW_NUM_COLUMNS = [1, 2, 3, 4, 6, 12] num_children = ChoiceField( label=_('Columns'), choices=[(i, ngettext_lazy('{0} column', '{0} columns', i).format(i)) for i in ROW_NUM_COLUMNS], initial=3, help_text=_('Number of columns to be created with this row.'), ) class Meta: untangled_fields = ['num_children']
def deactivate_short_urls(model_admin, request, queryset): """ Deactivates the selected URLs if they are all active, otherwise the user may be doing something wrong """ if queryset.filter(active=False).exists(): # already deactivated messages.error( request, _('Some of the selected URLs have already been deactivated.')) else: # deactivate; using update does one query, but does not call post_save/pre_save signals. We go for performance here updated_urls = queryset.update(active=False) messages.success( request, ngettext_lazy('Selected URL has been deactivated.', 'Selected URLs have been deactivated.', number=updated_urls))
def get_title(self, entry): """ Return the title with word count and number of comments. """ title = _('%(title)s (%(word_count)i words)') % \ {'title': entry.title, 'word_count': entry.word_count} reaction_count = int(entry.comment_count + entry.pingback_count + entry.trackback_count) if reaction_count: return ngettext_lazy( '%(title)s (%(reactions)i reaction)', '%(title)s (%(reactions)i reactions)', reaction_count) % \ {'title': title, 'reactions': reaction_count} return title
class SetDefaultHandler(LabelReplacingHandler): empty_message = _('OK: no instance of «{model}» have to be updated.') instances_message = ngettext_lazy( 'BEWARE: {count} instance of «{model}» uses «{instance}» & ' 'will be updated (the field will be set to «{fallback}»).', 'BEWARE: {count} instances of «{model}» use «{instance}» & ' 'will be updated (the field will be set to «{fallback}»).', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field = self.field model = field.remote_field.model try: default_value = field.remote_field.model.objects.get( pk=field.get_default()) except model.DoesNotExist: # TODO: test logger.exception( 'The default value for the field <%s> seems buggy.', field) default_value = False self.blocking = True self.default_value = default_value def _get_message_context(self): ctxt = super()._get_message_context() ctxt['fallback'] = self.default_value return ctxt def get_form_field(self): if self.blocking: field = self._build_message_formfield( _('ERROR: the default value is invalid. ' 'Please contact your administrator.')) elif not self.field_is_hidden: field = super().get_form_field() else: field = None return field def replacer(self, new_value): # if self.blocking: TODO ? return super().replacer(new_value=self.default_value)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) conditions = list(self.instance.policies.values_list("name", flat=True)) joined_conditions = conditions[0] if len(conditions) > 1: joined_conditions = _("{list} and {final}").format( list=", ".join(conditions[:-1]), final=conditions[-1]) self.fields["published"].help_text = ngettext_lazy( "This will publish the recommendation decision, plain text summary and supporting " "documents to the public {conditions} page", "This will publish the recommendation decision, plain text summary and supporting " "documents to the public {conditions} pages", len(conditions), ).format(conditions=escape(joined_conditions))
def page( head_list: List[dict], data_list: List[List[dict]], page: int, num_per_page: int ) -> Tuple[dict, Tuple[List[dict], List[List[dict]], int]]: num_objects = len(data_list) paginator = Paginator(data_list, num_per_page) num_pages = paginator.num_pages if page < 1 or page > num_pages: status = {'status': 404, 'status_text': _("Page out of range.")} return status, (head_list, data_list, 1) p = paginator.page(page) page_data_list = p.object_list msg = ngettext_lazy("%d Result Found", "%d Results Found") % num_objects status = {'status': 200, 'status_text': msg} return status, (head_list, page_data_list, num_pages)
def get_protected_messages_by_education_group_year(education_group_year): protected_message = [] # Count the number of enrollment count_enrollment = OfferEnrollment.objects.filter(education_group_year=education_group_year).count() if count_enrollment: protected_message.append( ngettext_lazy( "%(count_enrollment)d student is enrolled in the offer.", "%(count_enrollment)d students are enrolled in the offer.", count_enrollment ) % {"count_enrollment": count_enrollment} ) # Check if content is not empty if _have_contents_which_are_not_mandatory(education_group_year): protected_message.append(_("The content of the education group is not empty.")) if education_group_year.linked_with_epc: protected_message.append(_("Linked with EPC")) return protected_message
import calendar import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware, utc from django.utils.translation import gettext, ngettext_lazy TIMESINCE_CHUNKS = ( (60 * 60 * 24 * 365, ngettext_lazy('%d year', '%d years')), (60 * 60 * 24 * 30, ngettext_lazy('%d month', '%d months')), (60 * 60 * 24 * 7, ngettext_lazy('%d week', '%d weeks')), (60 * 60 * 24, ngettext_lazy('%d day', '%d days')), (60 * 60, ngettext_lazy('%d hour', '%d hours')), (60, ngettext_lazy('%d minute', '%d minutes')) ) def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """
def get_page_subtitle(self): teams_progress, adjs_progress = self.get_feedback_progress() total_missing = sum([progress.num_unsubmitted() for progress in teams_progress + adjs_progress]) return ngettext_lazy("%d missing feedback submission", "%d missing feedback submissions", total_missing) % (total_missing,)
_('Friendship Requests') _('Friend') _('Friends') _('Following Relationship') _('Following Relationships') _('Blocker Relationship') _('Blocked Relationships') # from django ngettext_lazy( singular='List contains %(show_value)d item, it should contain no more than %(limit_value)d.', plural='List contains %(show_value)d items, it should contain no more than %(limit_value)d.', number='limit_value' ) # from speedy.core pgettext_lazy(context="female", message='username (slug)') pgettext_lazy(context="male", message='username (slug)') pgettext_lazy(context="other", message='username (slug)') pgettext_lazy(context="female", message='Save Changes') pgettext_lazy(context="male", message='Save Changes') pgettext_lazy(context="other", message='Save Changes') pgettext_lazy(context="female", message="You can't change your username.") pgettext_lazy(context="male", message="You can't change your username.")
def get_help_text(self): return ngettext_lazy( singular="Your password must contain at most %(max_length)d character.", plural="Your password must contain at most %(max_length)d characters.", number=self.max_length, ) % {'max_length': self.max_length}
import calendar import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware, utc from django.utils.translation import gettext, ngettext_lazy TIME_STRINGS = { 'year': ngettext_lazy('%d year', '%d years'), 'month': ngettext_lazy('%d month', '%d months'), 'week': ngettext_lazy('%d week', '%d weeks'), 'day': ngettext_lazy('%d day', '%d days'), 'hour': ngettext_lazy('%d hour', '%d hours'), 'minute': ngettext_lazy('%d minute', '%d minutes'), } TIMESINCE_CHUNKS = ( (60 * 60 * 24 * 365, 'year'), (60 * 60 * 24 * 30, 'month'), (60 * 60 * 24 * 7, 'week'), (60 * 60 * 24, 'day'), (60 * 60, 'hour'), (60, 'minute'), ) def timesince(d, now=None, reversed=False, time_strings=None): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes".