Python django.utils.translation.gettext_lazy() Examples

The following are 30 code examples of django.utils.translation.gettext_lazy(). 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: account.py    From marsha with MIT License 7 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
Source File: utils.py    From bioforum with 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 #3
Source File: base.py    From bioforum with 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 #4
Source File: text.py    From bioforum with 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 #5
Source File: base.py    From bioforum with 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 #6
Source File: webdriver.py    From wagtail-tag-manager with 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 #7
Source File: filters.py    From bioforum with 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 #8
Source File: filters.py    From bioforum with 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 #9
Source File: webdriver.py    From wagtail-tag-manager with 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 #10
Source File: fields.py    From django-service-objects with 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 #11
Source File: views.py    From bioforum with 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
Source File: views.py    From bioforum with 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
Source File: array.py    From bioforum with 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
Source File: array.py    From bioforum with 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
Source File: api.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def mark_conversations_seen(self, request):
        """Trigger this endpoint to mark when the user has seen notifications about new messages in conversations"""
        self.check_permissions(request)
        meta, _ = ConversationMeta.objects.update_or_create({'conversations_marked_at': timezone.now()},
                                                            user=request.user)
        serializer = ConversationMetaSerializer(meta)
        return Response(serializer.data) 
Example #16
Source File: forms.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        url = self.cleaned_data.get('url')

        same_url = FlatPage.objects.filter(url=url)
        if self.instance.pk:
            same_url = same_url.exclude(pk=self.instance.pk)

        if same_url.exists():
            raise forms.ValidationError(
                _('存在相同的url  %(url)s'),
                code='duplicate_url',
                params={'url': url},
            )

        return super().clean() 
Example #17
Source File: views.py    From bioforum with MIT License 5 votes vote down vote up
def password_change(request,
                    template_name='registration/password_change_form.html',
                    post_change_redirect=None,
                    password_change_form=PasswordChangeForm,
                    extra_context=None):
    warnings.warn("The password_change() view is superseded by the "
                  "class-based PasswordChangeView().",
                  RemovedInDjango21Warning, stacklevel=2)
    if post_change_redirect is None:
        post_change_redirect = reverse('password_change_done')
    else:
        post_change_redirect = resolve_url(post_change_redirect)
    if request.method == "POST":
        form = password_change_form(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            # Updating the password logs out all other sessions for the user
            # except the current one.
            update_session_auth_hash(request, form.user)
            return HttpResponseRedirect(post_change_redirect)
    else:
        form = password_change_form(user=request.user)
    context = {
        'form': form,
        'title': _('Password change'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context) 
Example #18
Source File: views.py    From bioforum with MIT License 5 votes vote down vote up
def password_change_done(request,
                         template_name='registration/password_change_done.html',
                         extra_context=None):
    warnings.warn("The password_change_done() view is superseded by the "
                  "class-based PasswordChangeDoneView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'title': _('Password change successful'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context) 
Example #19
Source File: serializers.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(TokenObtainPairSerializer, self).__init__(*args, **kwargs)

        self.fields[self.username_field].help_text = _('Your username')
        self.fields['password'].help_text = _('your password') 
Example #20
Source File: serializers.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_conversation(self, conversation):
        if not conversation.can_access(self.context['request'].user):
            raise PermissionDenied(_('You are not in this conversation'))
        if conversation.is_closed:
            raise PermissionDenied(_('This conversation has been closed'))
        return conversation 
Example #21
Source File: __init__.py    From bioforum with MIT License 5 votes vote down vote up
def _description(self):
        return _('Field of type: %(field_type)s') % {
            'field_type': self.__class__.__name__
        } 
Example #22
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def unique_error_message(self, model_class, unique_check):
        opts = model_class._meta

        params = {
            'model': self,
            'model_class': model_class,
            'model_name': capfirst(opts.verbose_name),
            'unique_check': unique_check,
        }

        # A unique field
        if len(unique_check) == 1:
            field = opts.get_field(unique_check[0])
            params['field_label'] = capfirst(field.verbose_name)
            return ValidationError(
                message=field.error_messages['unique'],
                code='unique',
                params=params,
            )

        # unique_together
        else:
            field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
            params['field_labels'] = get_text_list(field_labels, _('and'))
            return ValidationError(
                message=_("%(model_name)s with this %(field_labels)s already exists."),
                code='unique_together',
                params=params,
            ) 
Example #23
Source File: boundfield.py    From bioforum with MIT License 5 votes vote down vote up
def label_tag(self, contents=None, attrs=None, label_suffix=None):
        """
        Wrap the given contents in a <label>, if the field has an ID attribute.
        contents should be mark_safe'd to avoid HTML escaping. If contents
        aren't given, use the field's HTML-escaped label.

        If attrs are given, use them as HTML attributes on the <label> tag.

        label_suffix overrides the form's label_suffix.
        """
        contents = contents or self.label
        if label_suffix is None:
            label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
                            else self.form.label_suffix)
        # Only add the suffix if the label does not end in punctuation.
        # Translators: If found as last label character, these punctuation
        # characters will prevent the default label_suffix to be appended to the label
        if label_suffix and contents and contents[-1] not in _(':?.!'):
            contents = format_html('{}{}', contents, label_suffix)
        widget = self.field.widget
        id_ = widget.attrs.get('id') or self.auto_id
        if id_:
            id_for_label = widget.id_for_label(id_)
            if id_for_label:
                attrs = dict(attrs or {}, **{'for': id_for_label})
            if self.field.required and hasattr(self.form, 'required_css_class'):
                attrs = attrs or {}
                if 'class' in attrs:
                    attrs['class'] += ' ' + self.form.required_css_class
                else:
                    attrs['class'] = self.form.required_css_class
            attrs = flatatt(attrs) if attrs else ''
            contents = format_html('<label{}>{}</label>', attrs, contents)
        else:
            contents = conditional_escape(contents)
        return mark_safe(contents) 
Example #24
Source File: models.py    From bioforum with MIT License 5 votes vote down vote up
def get_unique_error_message(self, unique_check):
        if len(unique_check) == 1:
            return gettext("Please correct the duplicate data for %(field)s.") % {
                "field": unique_check[0],
            }
        else:
            return gettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
                "field": get_text_list(unique_check, _("and")),
            } 
Example #25
Source File: utils.py    From bioforum with MIT License 5 votes vote down vote up
def pretty_name(name):
    """Convert 'first_name' to 'First name'."""
    if not name:
        return ''
    return name.replace('_', ' ').capitalize() 
Example #26
Source File: widgets.py    From bioforum with MIT License 5 votes vote down vote up
def value_omitted_from_data(self, data, files, name):
        return all(
            widget.value_omitted_from_data(data, files, name + '_%s' % i)
            for i, widget in enumerate(self.widgets)
        ) 
Example #27
Source File: widgets.py    From bioforum with MIT License 5 votes vote down vote up
def value_from_datadict(self, data, files, name):
        return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] 
Example #28
Source File: widgets.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self, attrs=None):
        choices = (
            ('1', _('Unknown')),
            ('2', _('Yes')),
            ('3', _('No')),
        )
        super().__init__(attrs, choices) 
Example #29
Source File: widgets.py    From bioforum with MIT License 5 votes vote down vote up
def _choice_has_empty_value(choice):
        """Return True if the choice's value is empty string or None."""
        value, _ = choice
        return (isinstance(value, str) and not bool(value)) or value is None 
Example #30
Source File: utils.py    From django-ads with 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')))