Python django.utils.translation.gettext() Examples
The following are 30
code examples of django.utils.translation.gettext().
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.utils.translation
, or try the search function
.
Example #1
Source File: list.py From bioforum with MIT License | 6 votes |
def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'): is_empty = not self.object_list.exists() else: is_empty = len(self.object_list) == 0 if is_empty: raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % { 'class_name': self.__class__.__name__, }) context = self.get_context_data() return self.render_to_response(context)
Example #2
Source File: dates.py From bioforum with MIT License | 6 votes |
def get_dated_queryset(self, **lookup): """ Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """ qs = self.get_queryset().filter(**lookup) date_field = self.get_date_field() allow_future = self.get_allow_future() allow_empty = self.get_allow_empty() paginate_by = self.get_paginate_by(qs) if not allow_future: now = timezone.now() if self.uses_datetime_field else timezone_today() qs = qs.filter(**{'%s__lte' % date_field: now}) if not allow_empty: # When pagination is enabled, it's better to do a cheap query # than to load the unpaginated queryset in memory. is_empty = len(qs) == 0 if paginate_by is None else not qs.exists() if is_empty: raise Http404(_("No %(verbose_name_plural)s available") % { 'verbose_name_plural': qs.model._meta.verbose_name_plural, }) return qs
Example #3
Source File: formsets.py From bioforum with MIT License | 6 votes |
def management_form(self): """Return the ManagementForm instance for this FormSet.""" if self.is_bound: form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError( _('ManagementForm data is missing or has been tampered with'), code='missing_management_form', ) else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num }) return form
Example #4
Source File: smtp.py From django-sitemessage with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None): """Constructs a MIME message from message and dispatch models.""" # TODO Maybe file attachments handling through `files` message_model context var. if subject is None: subject = '%s' % _('No Subject') if mtype == 'html': msg = self.mime_multipart() text_part = self.mime_multipart('alternative') text_part.attach(self.mime_text(strip_tags(text), _charset='utf-8')) text_part.attach(self.mime_text(text, 'html', _charset='utf-8')) msg.attach(text_part) else: msg = self.mime_text(text, _charset='utf-8') msg['From'] = self.from_email msg['To'] = to msg['Subject'] = subject if unsubscribe_url: msg['List-Unsubscribe'] = '<%s>' % unsubscribe_url return msg
Example #5
Source File: login.py From django-rest-registration with MIT License | 6 votes |
def logout(request): ''' Logs out the user. returns an error if the user is not authenticated. ''' user = request.user serializer = LogoutSerializer( data=request.data, context={'request': request}, ) serializer.is_valid(raise_exception=True) data = serializer.validated_data if should_authenticate_session(): auth.logout(request) if should_retrieve_token() and data['revoke_token']: auth_token_manager_cls = registration_settings.AUTH_TOKEN_MANAGER_CLASS auth_token_manager = auth_token_manager_cls() # noqa: E501 type: rest_registration.auth_token_managers.AbstractAuthTokenManager auth_token_manager.revoke_token(user) return get_ok_response(_("Logout successful"))
Example #6
Source File: accounts.py From silverstrike with MIT License | 6 votes |
def dispatch(self, request, *args, **kwargs): try: self.account = Account.objects.get(pk=self.kwargs['pk']) except Account.DoesNotExist: raise Http404(_('Account with id {} could not be found'.format(self.kwargs['pk']))) if self.account.account_type == Account.SYSTEM: return HttpResponse(_('Account not accessible'), status=403) if self.kwargs['period'] == 'all': self.dstart = None self.dend = None elif self.kwargs['period'] == 'custom': try: self.dstart = datetime.strptime(kwargs.pop('dstart'), '%Y-%m-%d').date() self.dend = datetime.strptime(kwargs.pop('dend'), '%Y-%m-%d').date() except ValueError: return HttpResponse(_('Nothing here...'), status=400) else: self.dend = date.today() self.dstart = self.dend - timedelta(days=30) return super(AccountView, self).dispatch(request, *args, **kwargs)
Example #7
Source File: list.py From bioforum with MIT License | 6 votes |
def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_("Page is not 'last', nor can it be converted to an int.")) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) })
Example #8
Source File: humanize.py From bioforum with MIT License | 6 votes |
def apnumber(value): """ For numbers 1-9, return the number spelled out. Otherwise, return the number. This follows Associated Press style. """ try: value = int(value) except (TypeError, ValueError): return value if not 0 < value < 10: return value return (_('one'), _('two'), _('three'), _('four'), _('five'), _('six'), _('seven'), _('eight'), _('nine'))[value - 1] # Perform the comparison in the default time zone when USE_TZ = True # (unless a specific time zone has been applied with the |timezone filter).
Example #9
Source File: api.py From silverstrike with MIT License | 6 votes |
def get_balances(request, dstart, dend): try: dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d').date() dend = datetime.datetime.strptime(dend, '%Y-%m-%d').date() except ValueError: return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd')) balance = Split.objects.personal().exclude_transfers().filter(date__lt=dstart).aggregate( models.Sum('amount'))['amount__sum'] or 0 splits = Split.objects.personal().exclude_transfers().date_range(dstart, dend).order_by('date') data_points = [] labels = [] days = (dend - dstart).days if days > 50: step = days / 50 + 1 else: step = 1 for split in splits: while split.date > dstart: data_points.append(balance) labels.append(datetime.datetime.strftime(dstart, '%Y-%m-%d')) dstart += datetime.timedelta(days=step) balance += split.amount data_points.append(balance) labels.append(datetime.datetime.strftime(dend, '%Y-%m-%d')) return JsonResponse({'labels': labels, 'data': data_points})
Example #10
Source File: tests.py From bioforum with MIT License | 5 votes |
def admin_login(self, username, password, login_url='/admin/'): """ Log in to the admin. """ self.selenium.get('%s%s' % (self.live_server_url, login_url)) username_input = self.selenium.find_element_by_name('username') username_input.send_keys(username) password_input = self.selenium.find_element_by_name('password') password_input.send_keys(password) login_text = _('Log in') self.selenium.find_element_by_xpath( '//input[@value="%s"]' % login_text).click() self.wait_page_loaded()
Example #11
Source File: widgets.py From bioforum with MIT License | 5 votes |
def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context['date_label'] = _('Date:') context['time_label'] = _('Time:') return context
Example #12
Source File: humanize.py From bioforum with MIT License | 5 votes |
def ordinal(value): """ Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer. """ try: value = int(value) except (TypeError, ValueError): return value suffixes = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th'), _('th')) if value % 100 in (11, 12, 13): # special case return mark_safe("%d%s" % (value, suffixes[0])) # Mark value safe so i18n does not break with <sup> or <sub> see #19988 return mark_safe("%d%s" % (value, suffixes[value % 10]))
Example #13
Source File: defaultfilters.py From bioforum with MIT License | 5 votes |
def yesno(value, arg=None): """ Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: arg = gettext('yes,no,maybe') bits = arg.split(',') if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no ################### # MISC # ###################
Example #14
Source File: dateformat.py From bioforum with MIT License | 5 votes |
def a(self): "'a.m.' or 'p.m.'" if self.data.hour > 11: return _('p.m.') return _('a.m.')
Example #15
Source File: text.py From bioforum with MIT License | 5 votes |
def get_valid_filename(s): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s)
Example #16
Source File: dateformat.py From bioforum with MIT License | 5 votes |
def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _('midnight') if self.data.minute == 0 and self.data.hour == 12: return _('noon') return '%s %s' % (self.f(), self.a())
Example #17
Source File: dateformat.py From bioforum with MIT License | 5 votes |
def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _('PM') return _('AM')
Example #18
Source File: defaultfilters.py From bioforum with MIT License | 5 votes |
def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = float(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_} elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value)
Example #19
Source File: static.py From bioforum with MIT License | 5 votes |
def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path).lstrip('/') fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): if show_indexes: return directory_index(path, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not os.path.exists(fullpath): raise Http404(_('"%(path)s" does not exist') % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(fullpath) content_type = content_type or 'application/octet-stream' response = FileResponse(open(fullpath, 'rb'), content_type=content_type) response["Last-Modified"] = http_date(statobj.st_mtime) if stat.S_ISREG(statobj.st_mode): response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding return response
Example #20
Source File: dates.py From bioforum with MIT License | 5 votes |
def _get_next_week(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ try: return date + datetime.timedelta(days=7 - self._get_weekday(date)) except OverflowError: raise Http404(_("Date out of range"))
Example #21
Source File: dates.py From bioforum with MIT License | 5 votes |
def get_week(self): """Return the week for which this view should display data.""" week = self.week if week is None: try: week = self.kwargs['week'] except KeyError: try: week = self.request.GET['week'] except KeyError: raise Http404(_("No week specified")) return week
Example #22
Source File: dates.py From bioforum with MIT License | 5 votes |
def get_day(self): """Return the day for which this view should display data.""" day = self.day if day is None: try: day = self.kwargs['day'] except KeyError: try: day = self.request.GET['day'] except KeyError: raise Http404(_("No day specified")) return day
Example #23
Source File: dates.py From bioforum with MIT License | 5 votes |
def _get_next_month(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ if date.month == 12: try: return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range")) else: return date.replace(month=date.month + 1, day=1)
Example #24
Source File: dates.py From bioforum with MIT License | 5 votes |
def _get_next_year(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ try: return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range"))
Example #25
Source File: dates.py From bioforum with MIT License | 5 votes |
def get_year(self): """Return the year for which this view should display data.""" year = self.year if year is None: try: year = self.kwargs['year'] except KeyError: try: year = self.request.GET['year'] except KeyError: raise Http404(_("No year specified")) return year
Example #26
Source File: detail.py From bioforum with MIT License | 5 votes |
def get_object(self, queryset=None): """ Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError("Generic detail view %s must be called with " "either an object pk or a slug." % self.__class__.__name__) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj
Example #27
Source File: notifymail.py From django-nyt with Apache License 2.0 | 5 votes |
def _send_user_notifications(self, context, connection): subject = _(nyt_settings.EMAIL_SUBJECT) message = render_to_string( 'emails/notification_email_message.txt', context ) email = mail.EmailMessage( subject, message, nyt_settings.EMAIL_SENDER, [context['user'].email], connection=connection ) self.logger.info("Sending to: %s" % context['user'].email) email.send(fail_silently=False)
Example #28
Source File: notifymail.py From django-nyt with Apache License 2.0 | 5 votes |
def _send_user_notifications(self, context, connection): subject = _(nyt_settings.EMAIL_SUBJECT) message = render_to_string( 'emails/notification_email_message.txt', context ) email = mail.EmailMessage( subject, message, nyt_settings.EMAIL_SENDER, [context['user'].email], connection=connection ) self.logger.info("Sending to: %s" % context['user'].email) email.send(fail_silently=False)
Example #29
Source File: api.py From silverstrike with MIT License | 5 votes |
def category_spending(request, dstart, dend): try: dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d') dend = datetime.datetime.strptime(dend, '%Y-%m-%d') except ValueError: return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd')) res = Split.objects.expense().past().date_range(dstart, dend).order_by('category').values( 'category__name').annotate(spent=models.Sum('amount')) if res: res = [(e['category__name'] or 'No category', abs(e['spent'])) for e in res if e['spent']] categories, spent = zip(*res) else: categories, spent = [], [] return JsonResponse({'categories': categories, 'spent': spent})
Example #30
Source File: views.py From pinax-documents with MIT License | 5 votes |
def get_object(self): folder = super().get_object() if not folder.can_share(self.request.user): raise Http404(_(f"Cannot share folder '{folder}'.")) return folder