Python django.utils.translation 模块,gettext_lazy() 实例源码

我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用django.utils.translation.gettext_lazy()

项目:django-rest-framework-sso    作者:namespace-ee    | 项目源码 | 文件源码
def authenticate_payload(payload):
    from rest_framework_sso.models import SessionToken

    user_model = get_user_model()

    if api_settings.VERIFY_SESSION_TOKEN:
        try:
            session_token = SessionToken.objects.\
                active().\
                select_related('user').\
                get(pk=payload.get(claims.SESSION_ID), user_id=payload.get(claims.USER_ID))
            user = session_token.user
        except SessionToken.DoesNotExist:
            raise exceptions.AuthenticationFailed(_('Invalid token.'))
    else:
        try:
            user = user_model.objects.get(pk=payload.get(claims.USER_ID))
        except user_model.DoesNotExist:
            raise exceptions.AuthenticationFailed(_('Invalid token.'))

    if not user.is_active:
        raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))

    return user
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def form_valid(self, form):
        if settings.ENABLE_USER_ACTIVATION:
            user = form.save(commit=False)
            user.is_active = False
            user.save()

            send_activation_email(self.request, user)

            messages.add_message(self.request, messages.SUCCESS,
                                 _('You are registered. To activate the account, follow the link sent to the mail.'))
        else:
            form.save()

            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')

            user = authenticate(username=username, password=raw_password)
            login(self.request, user)

            messages.add_message(self.request, messages.SUCCESS, _('You are successfully registered!'))

        return super(SignUpView, self).form_valid(form)
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def get_redirect_url(self, *args, **kwargs):
        assert 'code' in kwargs

        act = get_object_or_404(Activation, code=kwargs['code'])

        # Activate user's profile
        user = act.user
        user.is_active = True
        user.save()

        # Remove activation record, it is unneeded
        act.delete()

        messages.add_message(self.request, messages.SUCCESS, _('You have successfully activated your account!'))
        login(self.request, user)

        return super(ActivateView, self).get_redirect_url()
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def form_valid(self, form):
        user = self.request.user

        email = form.cleaned_data.get('email')
        email = email.lower()

        if hasattr(settings, 'EMAIL_ACTIVATION_AFTER_CHANGING') and settings.EMAIL_ACTIVATION_AFTER_CHANGING:
            send_activation_change_email(self.request, user, email)

            messages.add_message(self.request, messages.SUCCESS,
                                 _('To complete the change of mail, click on the link sent to it.'))
        else:
            user.email = email
            user.save()

            messages.add_message(self.request, messages.SUCCESS, _('Email successfully changed.'))

        return super(ChangeEmailView, self).form_valid(form)
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def send_activation_email(request, user):
    subject = _('Profile Activation')

    from_email = settings.DEFAULT_FROM_EMAIL
    current_site = get_current_site(request)
    domain = current_site.domain
    code = get_random_string(20)

    context = {
        'domain': domain,
        'code': code,
    }

    act = Activation()
    act.code = code
    act.user = user
    act.save()

    html_content = render_to_string('email/activation_profile.html', context=context, request=request)
    text_content = strip_tags(html_content)

    msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def send_activation_change_email(request, user, new_email):
    subject = _('Change email')

    from_email = settings.DEFAULT_FROM_EMAIL
    current_site = get_current_site(request)
    domain = current_site.domain
    code = get_random_string(20)

    context = {
        'domain': domain,
        'code': code,
    }

    act = Activation()
    act.code = code
    act.user = user
    act.email = new_email
    act.save()

    html_content = render_to_string('email/change_email.html', context=context, request=request)
    text_content = strip_tags(html_content)

    msg = EmailMultiAlternatives(subject, text_content, from_email, [user.email])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()
项目:2017.djangocon.eu    作者:djangocon    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(TalkSubmissionForm, self).__init__(*args, **kwargs)
        self.fields['author'].label = _('Your name')
        self.fields['email'].label = _('Your email')
        self.fields['author_bio'].label = _('Tell us about yourself')
        self.fields['proposal_title'].label = _('Your proposal\'s title')
        self.fields['proposal_abstract'].label = _('Abstract of your proposal')
        self.fields['proposal_why'].label = _('What the audience will get from your proposal?')
        self.fields['proposal_requirements'].label = _(
            'Do you have any special requirement for your talk?'
        )
        self.fields['proposal_audience'].label = _(
            'What\'s the intended audience of your proposal?')
        self.fields['mentor_wanted'].label = _('I\'d like a mentor')
        self.fields['mentor_offer'].label = _('I\'m volunteering as mentor')
        self.fields['pycon'].label = _('Do you want to submit your proposal to PyCon Italia 2017?')
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(
                    _("The two password fields didn't match."))
        return password2
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def clean_password(self):
        password = self.cleaned_data.get('password')
        if password:
            if not self.user.check_password(password):
                raise forms.ValidationError(_("Wrong password."))
        return password
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def clean_email(self):
        email = self.cleaned_data.get('email')

        if BitpollUser.objects.filter(email=email).count() > 0:
            raise forms.ValidationError(
                _('This address is already associated with an account.'))

        return email
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        try:
            return super(ResultView, self).get(request, *args, **kwargs)
        except Http404:
            messages.add_message(self.request, messages.WARNING,
                                 _('Check result does not exist (anymore)'))
            return HttpResponseRedirect(redirect_to=reverse_lazy(
                'django_datawatch_index'))
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        ctx = super(ResultAcknowledgeView, self).get_context_data(**kwargs)
        ctx.update(dict(action=_('Acknowledge')))
        return ctx
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def form_valid(self, form):
        response = super(ResultAcknowledgeView, self).form_valid(form)
        messages.add_message(self.request, messages.INFO, _('Successfully acknowledged'))
        return response
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        ctx = super(ResultConfigView, self).get_context_data(**kwargs)
        ctx.update(dict(action=_('Save')))
        return ctx
项目:django-datawatch    作者:RegioHelden    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        response = super(ResultRefreshView, self).get(request, *args, **kwargs)
        check = self.object.get_check_instance()
        datawatch.get_backend().run(slug=check.slug,
                                    identifier=self.object.identifier,
                                    async=False)
        messages.add_message(request, messages.INFO, _('Result has been refreshed'))
        return response
项目:zing    作者:evernote    | 项目源码 | 文件源码
def override_gettext(real_translation):
    """Replace Django's translation functions with safe versions."""
    translation.gettext = real_translation.gettext
    translation.ugettext = real_translation.ugettext
    translation.ngettext = real_translation.ngettext
    translation.ungettext = real_translation.ungettext
    translation.gettext_lazy = lazy(real_translation.gettext, str)
    translation.ugettext_lazy = lazy(real_translation.ugettext, unicode)
    translation.ngettext_lazy = lazy(real_translation.ngettext, str)
    translation.ungettext_lazy = lazy(real_translation.ungettext, unicode)
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def form_valid(self, form):
        user = form.get_user()

        activation = user.activation_set.get()
        activation.delete()

        send_activation_email(self.request, user)

        messages.add_message(self.request, messages.SUCCESS, _('A new activation code has been sent to your e-mail.'))

        return super(ReSendActivationCodeView, self).form_valid(form)
项目:simple-django-login-and-register    作者:egorsmkv    | 项目源码 | 文件源码
def form_valid(self, form):
        user = self.request.user

        user.first_name = form.cleaned_data.get('first_name')
        user.last_name = form.cleaned_data.get('last_name')
        user.save()

        messages.add_message(self.request, messages.SUCCESS, _('Profile data has been successfully updated.'))

        return super(ProfileEditView, self).form_valid(form)
项目:django-ads    作者:razisayyed    | 项目源码 | 文件源码
def get_zones_choices():
    for key in settings.ADS_ZONES:
        yield (key, gettext_lazy(settings.ADS_ZONES[key].get('name', 'Undefined')))
项目:adhocracy4    作者:liqd    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        defaults = {
            'verbose_name': _('Category'),
            'to': Category,
            'on_delete': models.SET_NULL,
            'null': True,
            'blank': True,
            'related_name': '+',
        }
        defaults.update(kwargs)
        super().__init__(**defaults)
项目:django-smart-lists    作者:plecto    | 项目源码 | 文件源码
def get_title(self):
        if self.model_field:
            return self.model_field.verbose_name.title()
        elif self.field_name == '__str__':
            return self.model._meta.verbose_name.title()
        try:
            field = getattr(self.model, self.field_name)
        except AttributeError as e:
            return self.field_name.title()
        if callable(field) and getattr(field, 'short_description', False):
            return field.short_description
        return self.field_name.replace("_", " ").title()
项目:django-smart-lists    作者:plecto    | 项目源码 | 文件源码
def __init__(self, model, field, column_id, query_params, ordering_query_param):
        self.model = model
        self.field_name = field

        self.order_field = None
        if self.field_name.startswith("_") and self.field_name != "__str__":
            raise SmartListException("Cannot use underscore(_) variables/functions in smart lists")
        try:
            self.model_field = self.model._meta.get_field(self.field_name)
            self.order_field = self.field_name
        except FieldDoesNotExist:
            self.model_field = None
            try:
                field = getattr(self.model, self.field_name)
                if callable(field) and getattr(field, 'admin_order_field', False):
                    self.order_field = getattr(field, 'admin_order_field')
                if callable(field) and getattr(field, 'alters_data', False):
                    raise SmartListException("Cannot use a function that alters data in smart list")
            except AttributeError:
                self.order_field = self.field_name
                pass  # This is most likely a .values() query set

        if self.order_field:
            self.order = SmartOrder(query_params=query_params, column_id=column_id, ordering_query_param=ordering_query_param)
        else:
            self.order = None
项目:django-smart-lists    作者:plecto    | 项目源码 | 文件源码
def get_values(self):
        values = []
        if self.model_field.choices:
            values = [
                SmartFilterValue(self.field_name, choice[1], choice[0], self.query_params) for choice in self.model_field.choices
            ]
        elif type(self.model_field) == BooleanField:
            values = [
                SmartFilterValue(self.field_name, choice[1], choice[0], self.query_params) for choice in (
                    (1, _('Yes')),
                    (0, _('No'))
                )
            ]

        return [SmartFilterValue(self.field_name, _("All"), None, self.query_params)] + values
项目:mes    作者:osess    | 项目源码 | 文件源码
def _get_group_choices(self):
        return [('', u'---------'), ('all', _('All users'))] + \
            [(group.pk, group.name) for group in Group.objects.all()]
项目:money-to-prisoners-send-money    作者:ministryofjustice    | 项目源码 | 文件源码
def validate_prisoner_number(value):
    if not prisoner_number_re.match(value):
        raise ValidationError(_('Incorrect prisoner number format'), code='invalid')
项目:2017.djangocon.eu    作者:djangocon    | 项目源码 | 文件源码
def clean(self):
        # ensure talk and workshop are NOT filled at the same time
        if self.talk and self.workshop:
            message = _('Please, select either a Talk or a Workshop, not both.')
            raise ValidationError({
                'talk': ValidationError(message=message, code='invalid'),
                'workshop': ValidationError(message=message, code='invalid'),
            })
项目:2017.djangocon.eu    作者:djangocon    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(WorkshopSubmissionForm, self).__init__(*args, **kwargs)
        self.fields['author'].label = _('Your name')
        self.fields['email'].label = _('Your email')
        self.fields['author_bio'].label = _('Tell us about yourself')
        self.fields['proposal_title'].label = _('Your proposal\'s title')
        self.fields['proposal_abstract'].label = _('Abstract of your proposal')
        self.fields['proposal_audience'].label = _(
            'What\'s the intended audience of your proposal?')
        self.fields['workshop_duration'].lable = _('How long is the workshop?')
项目:money-to-prisoners-send-money    作者:ministryofjustice    | 项目源码 | 文件源码
def get(self, request):
        prisoner_details = self.valid_form_data[DebitCardPrisonerDetailsView.url_name]
        amount_details = self.valid_form_data[DebitCardAmountView.url_name]

        amount_pence = int(amount_details['amount'] * 100)
        service_charge_pence = int(get_service_charge(amount_details['amount']) * 100)
        user_ip = request.META.get('HTTP_X_FORWARDED_FOR', '')
        user_ip = user_ip.split(',')[0].strip() or None

        payment_ref = None
        failure_context = {
            'short_payment_ref': _('Not known')
        }
        try:
            payment_client = PaymentClient()
            new_payment = {
                'amount': amount_pence,
                'service_charge': service_charge_pence,
                'recipient_name': prisoner_details['prisoner_name'],
                'prisoner_number': prisoner_details['prisoner_number'],
                'prisoner_dob': prisoner_details['prisoner_dob'].isoformat(),
                'ip_address': user_ip,
            }
            payment_ref = payment_client.create_payment(new_payment)
            failure_context['short_payment_ref'] = payment_ref[:8]

            new_govuk_payment = {
                'amount': amount_pence + service_charge_pence,
                'reference': payment_ref,
                'description': gettext('To this prisoner: %(prisoner_number)s' % prisoner_details),
                'return_url': site_url(
                    build_view_url(self.request, DebitCardConfirmationView.url_name)
                ) + '?payment_ref=' + payment_ref,
            }
            govuk_payment = payment_client.create_govuk_payment(payment_ref, new_govuk_payment)
            if govuk_payment:
                return redirect(get_link_by_rel(govuk_payment, 'next_url'))
        except OAuth2Error:
            logger.exception('Authentication error')
        except RequestException:
            logger.exception('Failed to create new payment (ref %s)' % payment_ref)

        return render(request, 'send_money/debit-card-failure.html', failure_context)