当前位置: 首页>>代码示例>>Python>>正文


Python translation.gettext方法代码示例

本文整理汇总了Python中django.utils.translation.gettext方法的典型用法代码示例。如果您正苦于以下问题:Python translation.gettext方法的具体用法?Python translation.gettext怎么用?Python translation.gettext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.translation的用法示例。


在下文中一共展示了translation.gettext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: logout

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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")) 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:23,代码来源:login.py

示例2: _build_message

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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 
开发者ID:idlesign,项目名称:django-sitemessage,代码行数:27,代码来源:smtp.py

示例3: dispatch

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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) 
开发者ID:agstrike,项目名称:silverstrike,代码行数:22,代码来源:accounts.py

示例4: get_balances

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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}) 
开发者ID:agstrike,项目名称:silverstrike,代码行数:27,代码来源:api.py

示例5: paginate_queryset

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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)
            }) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:24,代码来源:list.py

示例6: get

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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) 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:20,代码来源:list.py

示例7: get_dated_queryset

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:27,代码来源:dates.py

示例8: management_form

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:19,代码来源:formsets.py

示例9: apnumber

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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). 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:19,代码来源:humanize.py

示例10: get_object

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
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 
开发者ID:pinax,项目名称:pinax-documents,代码行数:7,代码来源:views.py

示例11: folder_created_message

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
def folder_created_message(self, request, folder):
        """
        Send messages.success message after successful folder creation.
        """
        messages.success(request, _(f"Folder {folder} was created")) 
开发者ID:pinax,项目名称:pinax-documents,代码行数:7,代码来源:hooks.py

示例12: document_created_message

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
def document_created_message(self, request, document):
        """
        Send messages.success message after successful document creation.
        """
        messages.success(request, _(f"Document {document} was created")) 
开发者ID:pinax,项目名称:pinax-documents,代码行数:7,代码来源:hooks.py

示例13: folder_shared_message

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
def folder_shared_message(self, request, user, folder):
        """
        Send messages.success message after successful share.
        """
        messages.success(request, _(f"Folder {folder} is now shared with {user}")) 
开发者ID:pinax,项目名称:pinax-documents,代码行数:7,代码来源:hooks.py

示例14: folder_unshared_message

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
def folder_unshared_message(self, request, user, folder):
        """
        Send messages.success message after successful unshare.
        """
        messages.success(request, _(f"User {user} no longer shares Folder {folder}")) 
开发者ID:pinax,项目名称:pinax-documents,代码行数:7,代码来源:hooks.py

示例15: folder_deleted_message

# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext [as 别名]
def folder_deleted_message(self, request, folder):
        """
        Send messages.success message after successful document deletion.
        """
        messages.success(request, _("Folder has been deleted")) 
开发者ID:pinax,项目名称:pinax-documents,代码行数:7,代码来源:hooks.py


注:本文中的django.utils.translation.gettext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。