django.utils.translation.gettext

Here are the examples of the python api django.utils.translation.gettext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

962 Examples 7

3 Source : views.py
with GNU General Public License v3.0
from abhishek-ram

    def get(self, request, *args, **kwargs):
        """Handle the GET call made to the AS2 server post endpoint."""
        return HttpResponse(
            _("To submit an AS2 message, you must POST the message to this URL")
        )

    def options(self, request, *args, **kwargs):

3 Source : serializers.py
with MIT License
from adfinis-sygroup

    def validate_group(self, group):
        request = self.context["request"]
        if group and group not in request.user.groups:
            raise exceptions.ValidationError(_(f"User is not member of group {group}"))

        return group

    def _sample_to_placeholders(self, sample_doc):

3 Source : tests.py
with GNU General Public License v3.0
from Aghoreshwar

    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()

    def get_css_value(self, selector, attribute):

3 Source : views.py
with GNU General Public License v3.0
from Aghoreshwar

def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    slug = url.partition('/')[0]
    try:
        f = feed_dict[slug]
    except KeyError:
        raise Http404(_("Slug %r isn't registered.") % slug)

    instance = f()
    instance.feed_url = getattr(f, 'feed_url', None) or request.path
    instance.title_template = f.title_template or ('feeds/%s_title.html' % slug)
    instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
    return instance(request)

3 Source : i18n.py
with GNU General Public License v3.0
from Aghoreshwar

    def render(self, context):
        context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES]
        return ''


class GetLanguageInfoNode(Node):

3 Source : dateformat.py
with GNU General Public License v3.0
from Aghoreshwar

    def a(self):
        "'a.m.' or 'p.m.'"
        if self.data.hour > 11:
            return _('p.m.')
        return _('a.m.')

    def A(self):

3 Source : dateformat.py
with GNU General Public License v3.0
from Aghoreshwar

    def A(self):
        "'AM' or 'PM'"
        if self.data.hour > 11:
            return _('PM')
        return _('AM')

    def B(self):

3 Source : dateformat.py
with GNU General Public License v3.0
from Aghoreshwar

    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())

    def s(self):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    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

    def get_next_year(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    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"))

    def _get_current_year(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    def get_month(self):
        """Return the month for which this view should display data."""
        month = self.month
        if month is None:
            try:
                month = self.kwargs['month']
            except KeyError:
                try:
                    month = self.request.GET['month']
                except KeyError:
                    raise Http404(_("No month specified"))
        return month

    def get_next_month(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    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)

    def _get_current_month(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    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

    def get_next_day(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    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

    def get_next_week(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

    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"))

    def _get_current_week(self, date):

3 Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar

def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
    """
    Get a datetime.date object given a format string and a year, month, and day
    (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = year_format + delim + month_format + delim + day_format
    datestr = str(year) + delim + str(month) + delim + str(day)
    try:
        return datetime.datetime.strptime(datestr, format).date()
    except ValueError:
        raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % {
            'datestr': datestr,
            'format': format,
        })


def _get_next_prev(generic_view, date, is_previous, period):

3 Source : tests.py
with MIT License
from Air-999

    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')
        with self.wait_page_loaded():
            self.selenium.find_element_by_xpath('//input[@value="%s"]' % login_text).click()

    def select_option(self, selector, value):

3 Source : views.py
with MIT License
from Air-999

def feed(request, url, feed_dict=None):
    """Provided for backwards compatibility."""
    if not feed_dict:
        raise Http404(_("No feeds are registered."))

    slug = url.partition('/')[0]
    try:
        f = feed_dict[slug]
    except KeyError:
        raise Http404(_('Slug %r isn’t registered.') % slug)

    instance = f()
    instance.feed_url = getattr(f, 'feed_url', None) or request.path
    instance.title_template = f.title_template or ('feeds/%s_title.html' % slug)
    instance.description_template = f.description_template or ('feeds/%s_description.html' % slug)
    return instance(request)

3 Source : dateformat.py
with MIT License
from Air-999

    def A(self):
        "'AM' or 'PM'"
        if self.data.hour > 11:
            return _('PM')
        return _('AM')

    def e(self):

3 Source : dates.py
with MIT License
from Air-999

def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'):
    """
    Get a datetime.date object given a format string and a year, month, and day
    (only year is mandatory). Raise a 404 for an invalid date.
    """
    format = year_format + delim + month_format + delim + day_format
    datestr = str(year) + delim + str(month) + delim + str(day)
    try:
        return datetime.datetime.strptime(datestr, format).date()
    except ValueError:
        raise Http404(_('Invalid date string “%(datestr)s” given format “%(format)s”') % {
            'datestr': datestr,
            'format': format,
        })


def _get_next_prev(generic_view, date, is_previous, period):

3 Source : serializers.py
with BSD 3-Clause "New" or "Revised" License
from ajithpmohan

    def validate(self, data):
        if data['password'] != data['password2']:
            raise serializers.ValidationError({'password': _('Passwords must match.')})
        return data

    def validate_groups(self, value):

3 Source : serializers.py
with BSD 3-Clause "New" or "Revised" License
from ajithpmohan

    def validate_groups(self, value):
        if not Group.objects.filter(name=value).exists():
            raise serializers.ValidationError(_('This field must be either DRIVER or RIDER'))
        return value

    def create(self, validated_data):

3 Source : validators.py
with BSD 3-Clause "New" or "Revised" License
from ajithpmohan

    def __call__(self, password):
        if len(password)   <   self.min_length:
            raise serializers.ValidationError(
                _(f"This password must contain at least {self.min_length} characters."),
                code='password_too_short',
            )


class MaximumLengthValidator(object):

3 Source : validators.py
with BSD 3-Clause "New" or "Revised" License
from ajithpmohan

    def __call__(self, password):
        if len(password) > self.max_length:
            raise serializers.ValidationError(
                _(f"This password must contain at most {self.max_length} characters."),
                code='password_too_long',
            )

3 Source : forms.py
with MIT License
from akashgiricse

    def clean(self):
        super(ChoiceInlineFormset, self).clean()

        correct_choices_count = 0
        for form in self.forms:
            if not form.is_valid():
                return

            if form.cleaned_data and form.cleaned_data.get('is_correct') is True:
                correct_choices_count += 1

        try:
            assert correct_choices_count == Question.ALLOWED_NUMBER_OF_CORRECT_CHOICES
        except AssertionError:
            raise forms.ValidationError(_('Exactly one correct choice is allowed.'))


User = get_user_model()

3 Source : account.py
with GNU General Public License v3.0
from arrobalytics

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = _('Update Account')
        context['header_title'] = _(f'Update Account: {self.object.code} - {self.object.name}')
        context['header_subtitle_icon'] = 'ic:twotone-account-tree'
        return context

    def get_form(self, form_class=None):

3 Source : account.py
with GNU General Public License v3.0
from arrobalytics

    def get_context_data(self, **kwargs):
        context = super(AccountModelCreateChildView, self).get_context_data()
        obj: AccountModel = self.get_object()
        context['page_title'] = _('Create Child Account')
        context['header_title'] = _('Create Child Account - %s' % obj)
        context['header_subtitle_icon'] = 'ic:twotone-account-tree'
        context['account'] = obj
        return context

    def get_form(self, form_class=None):

3 Source : views.py
with MIT License
from cds-snc

    def form_valid(self, form):
        is_valid = super().form_valid(form)
        if is_valid:
            messages.success(self.request, _("Log in code has been sent."))

        return is_valid


class InvitationView(Is2FAMixin, IsAdminMixin, ThrottledMixin, FormView):

3 Source : views.py
with MIT License
from cds-snc

    def delete(self, request, *args, **kwargs):
        response = super().delete(request, *args, **kwargs)
        messages.add_message(
            request,
            messages.SUCCESS,
            _("You deleted the account for ‘%(email)s’.")
            % {"email": self.object.email},
        )
        # This wont crash if no object is returned from the filtered query
        Invitation.objects.filter(email=self.object.email).delete()
        return response


def redirect_after_timed_out(request):

3 Source : views.py
with MIT License
from cds-snc

def redirect_after_timed_out(request):
    messages.add_message(
        request,
        messages.INFO,
        _("Your session timed out. Log in again to continue using the portal."),
        "logout",
    )
    return redirect(reverse_lazy("login"))


def password_reset_complete(request):

3 Source : views.py
with MIT License
from cds-snc

    def render(self, form=None, **kwargs):
        if not self.request.session.get("registrant_id"):
            messages.add_message(
                self.request,
                messages.ERROR,
                _("There has been an error, you need to confirm your email address"),
            )
            return redirect(reverse_lazy("register:registrant_email"))
        return super().render(form, **kwargs)

    def get_step_url(self, step):

3 Source : decorators.py
with Apache License 2.0
from Clivern

def stop_request_if_authenticated(function):
    def wrap(controller, request, *args, **kwargs):
        if request.user and request.user.is_authenticated:
            raise AccessForbidden(_("Error! Access forbidden for authenticated users."))
        return function(controller, request, *args, **kwargs)
    return wrap


def prevent_if_not_authenticated(function):

3 Source : decorators.py
with Apache License 2.0
from Clivern

def prevent_if_not_authenticated(function):
    def wrap(controller, request, *args, **kwargs):
        if not request.user or not request.user.is_authenticated:
            raise AccessForbidden(_("Oops! Access forbidden."))
        return function(controller, request, *args, **kwargs)
    return wrap


def push_metric(metric, count):

3 Source : sales_dude.py
with GNU General Public License v2.0
from costasiella

    def _sell_classpass_account_is_over_trial_pass_limit(account, organization_classpass):
        """
        Check if this account is allowed to purchase another trial card.
        """
        from ..models import AccountClasspass

        if not organization_classpass.trial_pass:
            # Nothing to do
            return

        if account.has_reached_trial_limit():
            raise Exception(_("Unable to sell classpass: Maximum number of trial passes reached for this account"))

    @staticmethod

3 Source : setup_dude.py
with GNU General Public License v2.0
from costasiella

    def setup(self):
        """
        Set the current version
        :return:
        """
        print("we're running the setup function")

        if self.complete == "T":
            return _("Setup already complete... setup will not be executed again.")
        # Set current version
        version_dude = VersionDude()
        version_dude.update_version()

        self.setting_setup_complete_obj.value = "T"
        self.setting_setup_complete_obj.save()

        return _("Setup complete!")

3 Source : account_genders.py
with GNU General Public License v2.0
from costasiella

def get_account_genders():
    return [
        ['', _("")],
        ['F', _("Female")],
        ['M', _("Male")],
        ['X', _("Other")]
    ]

3 Source : finance_order_statuses.py
with GNU General Public License v2.0
from costasiella

def get_finance_order_statuses():
    return (
        ('RECEIVED', _("Received")),
        ('AWAITING_PAYMENT', _("Awaiting payment")),
        ('PAID', _("Paid")),
        ('DELIVERED', _("Delivered")),
        ('CANCELLED', _("Cancelled")),
    )

3 Source : finance_payment_batch_statuses.py
with GNU General Public License v2.0
from costasiella

def get_finance_payment_batch_statuses():
    return (
        ('SENT_TO_BANK', _("Sent to Bank")),
        ('APPROVED', _("Approved")),
        ('AWAITING_APPROVAL', _("Awaiting approval")),
        ('REJECTED', _("Rejected")),
    )

3 Source : instructor_roles.py
with GNU General Public License v2.0
from costasiella

def get_instructor_roles():
    return [
        ['', _("Regular")],
        ['SUB', _("Substitute")],
        ['ASSISTANT', _("Assistant")],
        ['KARMA', _("Karma")]
    ]

3 Source : schedule_item_attendance_types.py
with GNU General Public License v2.0
from costasiella

def get_schedule_item_attendance_types():
    return [
        ['CLASSPASS', _("Classpass")],
        ['SUBSCRIPTION', _("Subscription")],
        ['COMPLEMENTARY', _("Complementary")],
        ['REVIEW', _("To be reviewed")],
        ['RECONCILE_LATER', _("Reconcile later")],
        ['SCHEDULE_EVENT_TICKET', _("Schedule event ticket")]
    ]

3 Source : schedule_item_otc_statuses.py
with GNU General Public License v2.0
from costasiella

def get_schedule_item_otc_statuses():
    return [
        ['', _("Regular")],
        ['CANCELLED', _("Cancelled")],
        ['OPEN', _("No instructor")]
    ]

3 Source : validity_tools.py
with GNU General Public License v2.0
from costasiella

def display_subscription_unit(subscription_unit):
    subscription_units = (
        ("WEEK", _("Week")),
        ("MONTH", _("Month"))
    )

    return_value = _("Subscription unit not found")

    for u in subscription_units:
        if subscription_unit == u[0]:
            return_value = u[1]

    return return_value

3 Source : account_bank_account_mandate.py
with GNU General Public License v2.0
from costasiella

def validate_create_update_input(input, update=False):
    """
    Validate input
    """ 
    result = {}

    # Fetch & check account
    if not update:
        # Create only
        rid = get_rid(input['account_bank_account'])
        account_bank_account = AccountBankAccount.objects.filter(id=rid.id).first()
        result['account_bank_account'] = account_bank_account
        if not account_bank_account:
            raise Exception(_('Invalid Account Bank Account ID!'))

    return result


class AccountBankAccountMandateNode(DjangoObjectType):

3 Source : account_classpass.py
with GNU General Public License v2.0
from costasiella

    def resolve_classes_remaining_display(self, info):
        if self.organization_classpass.unlimited:
            return _('Unlimited')
        else:
            return self.classes_remaining

    def resolve_is_expired(self, info):

3 Source : finance_payment_batch.py
with GNU General Public License v2.0
from costasiella

    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.delete_financepaymentbatch')

        rid = get_rid(input['id'])

        finance_payment_batch = FinancePaymentBatch.objects.filter(id=rid.id).first()
        if not finance_payment_batch:
            raise Exception(_('Invalid Finance Payment Batch ID!'))

        ok = finance_payment_batch.delete()

        return DeleteFinancePaymentBatch(ok=ok)


class FinancePaymentBatchMutation(graphene.ObjectType):

3 Source : finance_payment_batch_category.py
with GNU General Public License v2.0
from costasiella

    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.delete_financepaymentbatchcategory')

        rid = get_rid(input['id'])

        finance_payment_batch_category = FinancePaymentBatchCategory.objects.filter(id=rid.id).first()
        if not finance_payment_batch_category:
            raise Exception(_('Invalid Finance Payment BatchCategory ID!'))

        finance_payment_batch_category.archived = input['archived']
        finance_payment_batch_category.save()

        return ArchiveFinancePaymentBatchCategory(finance_payment_batch_category=finance_payment_batch_category)


class FinancePaymentBatchCategoryMutation(graphene.ObjectType):

3 Source : insight_finance_tax_rate_summary.py
with GNU General Public License v2.0
from costasiella

def validate_input(date_start, date_end):
    """
    Validate input
    """
    result = {}

    if date_end   <   date_start:
        raise Exception(_('dateEnd should be >= dateStart'))

    return result

class InsightFinanceTaxRateSummaryQuery(graphene.ObjectType):

3 Source : organization_appointment_category.py
with GNU General Public License v2.0
from costasiella

    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.add_organizationappointmentcategory')

        errors = []
        if not len(input['name']):
            print('validation error found')
            raise GraphQLError(_('Name is required'))

        organization_appointment_category = OrganizationAppointmentCategory(
            name=input['name'], 
            display_public=input['display_public']
        )
        organization_appointment_category.save()

        return CreateOrganizationAppointmentCategory(organization_appointment_category=organization_appointment_category)


class UpdateOrganizationAppointmentCategory(graphene.relay.ClientIDMutation):

3 Source : organization_classtype.py
with GNU General Public License v2.0
from costasiella

def validate_update_image_input(input):
    """
    Validate input
    """
    result = {}

    if 'image' in input or 'image_file_name' in input:
        if not (input.get('image', None) and input.get('image_file_name', None)):
            raise Exception(_('When setting "image" or "imageFileName", both fields need to be present and set'))

    return result

class UploadOrganizationClasstypeImage(graphene.relay.ClientIDMutation):

3 Source : organization_discovery.py
with GNU General Public License v2.0
from costasiella

    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.add_organizationdiscovery')

        errors = []
        if not len(input['name']):
            print('validation error found')
            raise GraphQLError(_('Name is required'))

        organization_discovery = OrganizationDiscovery(
            name=input['name'], 
        )

        organization_discovery.save()

        return CreateOrganizationDiscovery(organization_discovery=organization_discovery)


class UpdateOrganizationDiscovery(graphene.relay.ClientIDMutation):

See More Examples