Python django.utils.translation.gettext_lazy() Examples

The following are 30 code examples for showing how to use django.utils.translation.gettext_lazy(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.translation , or try the search function .

Example 1
Project: marsha   Author: openfun   File: account.py    License: MIT License 6 votes vote down vote up
def save(self, *args, **kwargs):
        """Generate the oauth consumer key and shared secret randomly upon creation.

        Parameters
        ----------
        args : list
            Passed onto parent's `save` method
        kwargs: dict
            Passed onto parent's `save` method

        """
        self.full_clean()
        if not self.oauth_consumer_key:
            self.oauth_consumer_key = "".join(
                secrets.choice(OAUTH_CONSUMER_KEY_CHARS)
                for _ in range(OAUTH_CONSUMER_KEY_SIZE)
            )
        if not self.shared_secret:
            self.shared_secret = "".join(
                secrets.choice(SHARED_SECRET_CHARS) for _ in range(SHARED_SECRET_SIZE)
            )
        super().save(*args, **kwargs) 
Example 2
Project: django-service-objects   Author: mixxorz   File: fields.py    License: MIT License 6 votes vote down vote up
def clean(self, values):
        if not values and values is not False:
            if self.required:
                raise ValidationError(self.error_required % {
                    'values': values
                })
            else:
                return values

        try:
            _ = iter(values)
        except TypeError:
            raise ValidationError(self.error_non_iterable)

        for value in values:
            self.check_type(value)
            self.check_unsaved(value)
        return values 
Example 3
Project: wagtail-tag-manager   Author: jberghoef   File: webdriver.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_webdriver_cookie(self, cookie):
        expiry = datetime.fromtimestamp(cookie.get("expiry", self.now))

        obj, created = CookieDeclaration.objects.update_or_create(
            name=cookie.get("name"),
            domain=cookie.get("domain"),
            defaults={
                "security": CookieDeclaration.INSECURE_COOKIE
                if cookie.get("httpOnly")
                else CookieDeclaration.SECURE_COOKIE,
                "purpose": _("Unknown"),
                "duration": self.chop_microseconds(expiry - self.now),
            },
        )

        self.increment_status(created) 
Example 4
Project: wagtail-tag-manager   Author: jberghoef   File: webdriver.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_requests_cookie(self, cookie):
        cookie_expires = getattr(cookie, "expires")
        expiry = datetime.fromtimestamp(cookie_expires) if cookie_expires else self.now
        obj, created = CookieDeclaration.objects.update_or_create(
            name=getattr(cookie, "name"),
            domain=getattr(cookie, "domain"),
            defaults={
                "security": CookieDeclaration.SECURE_COOKIE
                if getattr(cookie, "secure", False)
                else CookieDeclaration.INSECURE_COOKIE,
                "purpose": _("Unknown"),
                "duration": self.chop_microseconds(expiry - self.now),
            },
        )

        self.increment_status(created) 
Example 5
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception as exc:
            raise ValidationError(
                _('%(datetime)s couldn\'t be interpreted '
                  'in time zone %(current_timezone)s; it '
                  'may be ambiguous or it may not exist.'),
                code='ambiguous_timezone',
                params={'datetime': value, 'current_timezone': current_timezone}
            ) from exc
    return value 
Example 6
Project: bioforum   Author: reBiocoder   File: text.py    License: MIT License 6 votes vote down vote up
def get_text_list(list_, last_word=gettext_lazy('or')):
    """
    >>> get_text_list(['a', 'b', 'c', 'd'])
    'a, b, c or d'
    >>> get_text_list(['a', 'b', 'c'], 'and')
    'a, b and c'
    >>> get_text_list(['a', 'b'], 'and')
    'a and b'
    >>> get_text_list(['a'])
    'a'
    >>> get_text_list([])
    ''
    """
    if len(list_) == 0:
        return ''
    if len(list_) == 1:
        return str(list_[0])
    return '%s %s %s' % (
        # Translators: This string is used as a separator between list elements
        _(', ').join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1])
    ) 
Example 7
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def _check_column_name_clashes(cls):
        # Store a list of column names which have already been used by other fields.
        used_column_names = []
        errors = []

        for f in cls._meta.local_fields:
            _, column_name = f.get_attname_column()

            # Ensure the column name is not already in use.
            if column_name and column_name in used_column_names:
                errors.append(
                    checks.Error(
                        "Field '%s' has column name '%s' that is used by "
                        "another field." % (f.name, column_name),
                        hint="Specify a 'db_column' for the field.",
                        obj=cls,
                        id='models.E007'
                    )
                )
            else:
                used_column_names.append(column_name)

        return errors 
Example 8
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def _check_model_name_db_lookup_clashes(cls):
        errors = []
        model_name = cls.__name__
        if model_name.startswith('_') or model_name.endswith('_'):
            errors.append(
                checks.Error(
                    "The model name '%s' cannot start or end with an underscore "
                    "as it collides with the query lookup syntax." % model_name,
                    obj=cls,
                    id='models.E023'
                )
            )
        elif LOOKUP_SEP in model_name:
            errors.append(
                checks.Error(
                    "The model name '%s' cannot contain double underscores as "
                    "it collides with the query lookup syntax." % model_name,
                    obj=cls,
                    id='models.E024'
                )
            )
        return errors 
Example 9
Project: bioforum   Author: reBiocoder   File: filters.py    License: MIT License 6 votes vote down vote up
def choices(self, changelist):
        yield {
            'selected': self.lookup_val is None and not self.lookup_val_isnull,
            'query_string': changelist.get_query_string(
                {},
                [self.lookup_kwarg, self.lookup_kwarg_isnull]
            ),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_val == str(pk_val),
                'query_string': changelist.get_query_string({
                    self.lookup_kwarg: pk_val,
                }, [self.lookup_kwarg_isnull]),
                'display': val,
            }
        if self.include_empty_choice:
            yield {
                'selected': bool(self.lookup_val_isnull),
                'query_string': changelist.get_query_string({
                    self.lookup_kwarg_isnull: 'True',
                }, [self.lookup_kwarg]),
                'display': self.empty_value_display,
            } 
Example 10
Project: bioforum   Author: reBiocoder   File: filters.py    License: MIT License 6 votes vote down vote up
def choices(self, changelist):
        for lookup, title in (
                (None, _('All')),
                ('1', _('Yes')),
                ('0', _('No'))):
            yield {
                'selected': self.lookup_val == lookup and not self.lookup_val2,
                'query_string': changelist.get_query_string({
                    self.lookup_kwarg: lookup,
                }, [self.lookup_kwarg2]),
                'display': title,
            }
        if isinstance(self.field, models.NullBooleanField):
            yield {
                'selected': self.lookup_val2 == 'True',
                'query_string': changelist.get_query_string({
                    self.lookup_kwarg2: 'True',
                }, [self.lookup_kwarg]),
                'display': _('Unknown'),
            } 
Example 11
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
def password_reset_done(request,
                        template_name='registration/password_reset_done.html',
                        extra_context=None):
    warnings.warn("The password_reset_done() view is superseded by the "
                  "class-based PasswordResetDoneView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'title': _('Password reset sent'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)


# Doesn't need csrf_protect since no-one can guess the URL 
Example 12
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
def password_reset_complete(request,
                            template_name='registration/password_reset_complete.html',
                            extra_context=None):
    warnings.warn("The password_reset_complete() view is superseded by the "
                  "class-based PasswordResetCompleteView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'login_url': resolve_url(settings.LOGIN_URL),
        'title': _('Password reset complete'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)


# Class-based password reset views
# - PasswordResetView sends the mail
# - PasswordResetDoneView shows a success message for the above
# - PasswordResetConfirmView checks the link the user clicked and
#   prompts for a new password
# - PasswordResetCompleteView shows a success message for the above 
Example 13
Project: bioforum   Author: reBiocoder   File: array.py    License: MIT License 6 votes vote down vote up
def get_context(self, name, value, attrs=None):
        attrs = {} if attrs is None else attrs
        context = super().get_context(name, value, attrs)
        if self.is_localized:
            self.widget.is_localized = self.is_localized
        value = value or []
        context['widget']['subwidgets'] = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i in range(max(len(value), self.size)):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            context['widget']['subwidgets'].append(
                self.widget.get_context(name + '_%s' % i, widget_value, final_attrs)['widget']
            )
        return context 
Example 14
Project: bioforum   Author: reBiocoder   File: array.py    License: MIT License 6 votes vote down vote up
def get_transform(self, name):
        transform = super().get_transform(name)
        if transform:
            return transform
        if '_' not in name:
            try:
                index = int(name)
            except ValueError:
                pass
            else:
                index += 1  # postgres uses 1-indexing
                return IndexTransformFactory(index, self.base_field)
        try:
            start, end = name.split('_')
            start = int(start) + 1
            end = int(end)  # don't add one here because postgres slices are weird
        except ValueError:
            pass
        else:
            return SliceTransformFactory(start, end) 
Example 15
Project: django-ads   Author: razisayyed   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_zones_choices():
    for key in sorted(settings.ADS_ZONES):
        yield (key, _(settings.ADS_ZONES[key].get('name', 'Undefined'))) 
Example 16
Project: marsha   Author: openfun   File: playlist.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        result = f"{self.title}"
        if self.deleted:
            result = _("{:s} [deleted]").format(result)
        return result 
Example 17
Project: marsha   Author: openfun   File: playlist.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        kwargs = {"source": self.source_playlist, "target": self.target_playlist}
        if self.deleted:
            return _("{source} was portable to {target}").format(**kwargs)
        return _("{source} is portable to {target}").format(**kwargs) 
Example 18
Project: marsha   Author: openfun   File: video.py    License: MIT License 5 votes vote down vote up
def get_source_s3_key(self, stamp=None):
        """Compute the S3 key in the source bucket.

        It is built from the video ID + ID of the timed text track + version stamp + language +
        closed captioning flag.

        Parameters
        ----------
        stamp: Type[string]
            Passing a value for this argument will return the source S3 key for the timed text
            track assuming its active stamp is set to this value. This is useful to create an
            upload policy for this prospective version of the track, so that the client can
            upload the file to S3 and the confirmation lambda can set the `uploaded_on` field
            to this value only after the file upload and processing is successful.

        Returns
        -------
        string
            The S3 key for the timed text files in the source bucket, where uploaded files are
            stored before they are converted and copied to the destination bucket.

        """
        stamp = stamp or to_timestamp(self.uploaded_on)
        return "{video!s}/timedtexttrack/{pk!s}/{stamp:s}_{language:s}{mode:s}".format(
            video=self.video.pk,
            pk=self.pk,
            stamp=stamp,
            language=self.language,
            mode="_{:s}".format(self.mode) if self.mode else "",
        ) 
Example 19
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        result = f"{self.username}"
        if self.email:
            result += f" ({self.email})"
        if self.deleted:
            result += _(" [deleted]")
        return result 
Example 20
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def clean(self):
        """Clean instance fields before saving."""
        if self.consumer_site and self.playlist:
            message = _(
                "You should set either a Consumer Site or a Playlist, but not both."
            )
            raise ValidationError({"__all__": [message]})
        if not (self.consumer_site or self.playlist):
            raise ValidationError(
                {"__all__": [_("You must set either a Consumer Site or a Playlist.")]}
            )
        return super().clean()

    # pylint: disable=arguments-differ 
Example 21
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        result = f"{self.name} ({self.domain})"
        if self.deleted:
            result = _("{:s} [deleted]").format(result)
        return result 
Example 22
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        kwargs = {"source": self.source_site, "target": self.target_site}
        if self.deleted:
            return _("{source} was portable to {target}").format(**kwargs)
        return _("{source} is portable to {target}").format(**kwargs) 
Example 23
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        kwargs: dict = {
            "user": self.user,
            "consumer_site": self.consumer_site,
            "role": self.get_role_display(),
        }
        if self.deleted:
            return _("{user} was {role} of {consumer_site}").format(**kwargs)
        return _("{user} is {role} of {consumer_site}").format(**kwargs) 
Example 24
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        kwargs = {
            "organization": self.organization,
            "consumer_site": self.consumer_site,
        }
        if self.deleted:
            return _("{organization} was in {consumer_site}").format(**kwargs)
        return _("{organization} is in {consumer_site}").format(**kwargs) 
Example 25
Project: marsha   Author: openfun   File: account.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        kwargs = {
            "user": self.user,
            "organization": self.organization,
            "role": self.get_role_display(),
        }
        if self.deleted:
            return _("{user} was {role} of {organization}").format(**kwargs)

        return _("{user} is {role} of {organization}").format(**kwargs) 
Example 26
Project: marsha   Author: openfun   File: file.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        """Get the string representation of an instance."""
        result = f"{self.title}"
        if self.deleted:
            result = _("{:s} [deleted]").format(result)
        return result 
Example 27
Project: django-hashid-field   Author: nshafer   File: field.py    License: MIT License 5 votes vote down vote up
def contribute_to_class(self, cls, name, **kwargs):
        super().contribute_to_class(cls, name, **kwargs)
        # setattr(cls, "_" + self.attname, getattr(cls, self.attname))
        setattr(cls, self.attname, HashidDescriptor(self.attname, hashids=self._hashids)) 
Example 28
Project: koku   Author: project-koku   File: validators.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, attrs):
        """Enforce validation of all relevant fields."""
        start_date = attrs["start_date"]
        end_date = attrs["end_date"]
        if end_date < start_date:
            bad_items = {
                "start_date": _('"start_date" must be older than "end_date".'),
                "end_date": _('"end_date" must not be older than "start_date".'),
            }
            raise ValidationError(bad_items, code="bad_request")
        if self.pending_instance_exists(start_date, end_date):
            exists_message = _(
                "A pending or processing data export already exists with the given " '"start_date" and "end_date".'
            )
            raise ValidationError(exists_message, code="bad_request") 
Example 29
Project: django-sitemessage   Author: idlesign   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_value(cls, value: str):
        try:
            return json.loads(value)

        except ValueError:
            raise exceptions.ValidationError(
                _('Value `%r` is not a valid context.') % value,
                code='invalid_context', params={'value': value}) 
Example 30
Project: django-sundial   Author: charettes   File: zones.py    License: MIT License 5 votes vote down vote up
def _label_zone(zone):
    offset = datetime.now(pytz.timezone('/'.join(zone))).strftime('%z')
    return _("%(name)s (GMT%(offset)s)") % {
        'name': _(zone[-1].replace('_', ' ')),
        'offset': offset,
    }