我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用django.utils.translation.gettext()。
def _default_text(self): if not self.use_default: note = "" else: if self.default == "": note = _('Default value: ""') elif self.choices: work = [] for x in self.choices: try: if x[0] == self.default or x[0] in self.default: work.append('%s' % str(smart_str(x[1]))) except TypeError: continue note = gettext('Default value: ') + ", ".join(work) else: note = _("Default value: %s") % str(self.default) return note
def page_not_found(request, template_name='404.html'): context = { 'request_path': request.path, 'error': { 'title': _('Page not found'), 'message': _("We tried but couldn't find this page, sorry."), }, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def server_error(request, template_name='500.html'): if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json': return JsonResponse({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), } }, status=500) try: template = loader.get_template(template_name) except TemplateDoesNotExist: return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>') return HttpResponseServerError(template.render({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), 'message': message, 'sentry': _('Fault code: #'), } }))
def _get_request_token(self): """ Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token """ if self.request_token is None: get_params = {} if self.parameters: get_params.update(self.parameters) get_params['oauth_callback'] \ = self.request.build_absolute_uri(self.callback_url) rt_url = self.request_token_url + '?' + urlencode(get_params) oauth = OAuth1(self.consumer_key, client_secret=self.consumer_secret) response = requests.post(url=rt_url, auth=oauth) if response.status_code not in [200, 201]: raise OAuthError( _('Invalid response while obtaining request token' ' from "%s".') % get_token_prefix( self.request_token_url)) self.request_token = dict(parse_qsl(response.text)) self.request.session['oauth_%s_request_token' % get_token_prefix( self.request_token_url)] = self.request_token return self.request_token
def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. """ access_token = self._get_at_from_session() oauth = OAuth1( self.consumer_key, client_secret=self.secret_key, resource_owner_key=access_token['oauth_token'], resource_owner_secret=access_token['oauth_token_secret']) response = getattr(requests, method.lower())(url, auth=oauth, headers=headers, params=params) if response.status_code != 200: raise OAuthError( _('No access to private resources at "%s".') % get_token_prefix(self.request_token_url)) return response.text
def server_error(request, template_name='500.html'): if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json': return JsonResponse({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), } }, status=500) try: template = loader.get_template(template_name) except TemplateDoesNotExist: return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return HttpResponseServerError(template.render({ 'sentry': sentry_id_from_request(request), 'error': { 'title': _('Something went wrong'), 'message': ('%s' % _('Something went wrong on our side... \n Please hold on while we fix it.')).replace('\n', '<br>'), 'sentry': _('Fault code: #'), } }))
def support_links(_): return { 'support_links': [ { 'url': reverse('terms'), 'title': gettext('Terms and conditions'), }, { 'url': reverse('cookies'), 'title': gettext('Cookies'), }, { 'url': reverse('submit_ticket'), 'title': gettext('Feedback'), }, ] }
def _get_request_token(self): """ Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token """ if self.request_token is None: get_params = {} if self.parameters: get_params.update(self.parameters) get_params['oauth_callback'] \ = self.request.build_absolute_uri(self.callback_url) rt_url = self.request_token_url + '?' + urlencode(get_params) oauth = OAuth1(self.consumer_key, client_secret=self.consumer_secret) response = requests.post(url=rt_url, auth=oauth) if response.status_code not in [200, 201]: raise OAuthError( _('Invalid response while obtaining request token from "%s".') % get_token_prefix(self.request_token_url)) self.request_token = dict(parse_qsl(response.text)) self.request.session['oauth_%s_request_token' % get_token_prefix(self.request_token_url)] = self.request_token return self.request_token
def get_actions(self): actions = super().get_actions() nested_update(actions, { 'built_in': { 'endorse_members': {}, }, 'click': { 'edit_note': { 'localName': _('Edit member note'), 'css': 'btn-warning', }, }, 'glyphicon': { 'quick_endorse': { 'localName': _('Quick endorsement'), 'css': 'glyphicon-cloud-upload', }, 'quick_disendorse': { 'localName': _('Quick disendorsement'), 'css': 'glyphicon-cloud-download', } } }) return actions
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)
def get_language_bidi(): """Override for Django's get_language_bidi that's aware of more RTL languages. """ return gettext.language_dir(translation.get_language()) == 'rtl'
def hijack_translation(): """Sabotage Django's fascist linguistical regime.""" # Override functions that check if language is known to Django translation.check_for_language = lambda lang_code: True trans_real.check_for_language = lambda lang_code: True translation.get_language_from_request = get_language_from_request # Override django's inadequate bidi detection translation.get_language_bidi = get_language_bidi # We hijack gettext functions to install the safe variable formatting # override override_gettext(gettext)
def get_access_token(self): """ Obtain the access token to access private resources at the API endpoint. """ if self.access_token is None: request_token = self._get_rt_from_session() oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=request_token['oauth_token'], resource_owner_secret=request_token['oauth_token_secret']) at_url = self.access_token_url # Passing along oauth_verifier is required according to: # http://groups.google.com/group/twitter-development-talk/browse_frm/thread/472500cfe9e7cdb9# # Though, the custom oauth_callback seems to work without it? oauth_verifier = get_request_param(self.request, 'oauth_verifier') if oauth_verifier: at_url = at_url + '?' + urlencode( {'oauth_verifier': oauth_verifier}) response = requests.post(url=at_url, auth=oauth) if response.status_code not in [200, 201]: raise OAuthError( _('Invalid response while obtaining access token' ' from "%s".') % get_token_prefix( self.request_token_url)) self.access_token = dict(parse_qsl(response.text)) self.request.session['oauth_%s_access_token' % get_token_prefix( self.request_token_url)] = self.access_token return self.access_token
def _get_rt_from_session(self): """ Returns the request token cached in the session by ``_get_request_token`` """ try: return self.request.session['oauth_%s_request_token' % get_token_prefix( self.request_token_url)] except KeyError: raise OAuthError(_('No request token saved for "%s".') % get_token_prefix(self.request_token_url))
def _get_at_from_session(self): """ Get the saved access token for private resources from the session. """ try: return self.request.session['oauth_%s_access_token' % get_token_prefix( self.request_token_url)] except KeyError: raise OAuthError( _('No access token saved for "%s".') % get_token_prefix(self.request_token_url))
def quantity_validator(number): if int(number) > 0: return number else: raise ValidationError(_("Antall kan ikke være negativt."), code='Invalid') # TODO fyll form med det man hadde isted, når man gjør feil.
def delete_all_items(items: str): """ Sets the visible field to False Args: items: id's separated with '_' (also at the end) """ for item_id in items.split('_'): if item_id: item = get_object_or_404(Item, pk=item_id) item.visible = False item.save()
def change_tags(items_str: str, new_tags: str): """ Updates the tags for items in item_str to the tags in new_tags Args: items_str, new_tags: id's separated with '_' (also at the end) """ tags = [get_object_or_404(Tag, pk=tag_id) for tag_id in new_tags.split('_')[:-1]] items = [get_object_or_404(Item, pk=item_id) for item_id in items_str.split('_')[:-1]] for item in items: item.tags.remove(*item.tags.all()) item.tags.add(*tags) item.save()
def form_valid(self, form): email = form.cleaned_data['email'] context = self.get_context_data(site_url=settings.START_PAGE_URL, feedback_url=site_url(reverse('submit_ticket')), help_url=site_url(reverse('send_money:help'))) context.pop('form', None) context.pop('view', None) send_email( email, 'send_money/email/bank-transfer-reference.txt', gettext('Send money to someone in prison: ' 'Your prisoner reference is %(bank_transfer_reference)s') % context, context=context, html_template='send_money/email/bank-transfer-reference.html' ) return super().form_valid(form)
def process_exception(self, request, exception): if isinstance(exception, Unauthorized): logger.error( 'Shared send money user was not authorised to access api' ) raise Http404(_('Could not connect to service, please try again later'))
def get_access_token(self): """ Obtain the access token to access private resources at the API endpoint. """ if self.access_token is None: request_token = self._get_rt_from_session() oauth = OAuth1(self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=request_token['oauth_token'], resource_owner_secret=request_token['oauth_token_secret']) at_url = self.access_token_url # Passing along oauth_verifier is required according to: # http://groups.google.com/group/twitter-development-talk/browse_frm/thread/472500cfe9e7cdb9# # Though, the custom oauth_callback seems to work without it? oauth_verifier = get_request_param(self.request, 'oauth_verifier') if oauth_verifier: at_url = at_url + '?' + urlencode({'oauth_verifier': oauth_verifier}) response = requests.post(url=at_url, auth=oauth) if response.status_code not in [200, 201]: raise OAuthError( _('Invalid response while obtaining access token from "%s".') % get_token_prefix(self.request_token_url)) self.access_token = dict(parse_qsl(response.text)) self.request.session['oauth_%s_access_token' % get_token_prefix(self.request_token_url)] = self.access_token return self.access_token
def get_actions(self): actions = super().get_actions() actions['built_in']['save_equipment'] = {} actions['glyphicon']['add_equipment'] = { 'localName': _('Add club equipment'), 'css': 'glyphicon-wrench', } return actions # Creates AJAX ClubEquipmentForm bound to particular Club instance.
def validate_video(value): if os.name == 'nt': magic_object = magic.Magic(magic_file='magic', mime=True) mime = magic_object.from_buffer(value.file.read(1024)) else: mime = magic.from_buffer(value.file.read(1024), mime=True) value.file.seek(0) if not mime.startswith('video/'): raise ValidationError(_(app_settings.INVALID_VIDEO_ERROR_MESSAGE))
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)