本文整理汇总了Python中django.utils.translation._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: form_valid
def form_valid(self, form):
cg = self.contactgroup
request = self.request
if not cg.userperms & perms.WRITE_FILES:
raise PermissionDenied
upfile = request.FILES['file_to_upload']
# name has already been sanitized by UploadedFile._set_name
path = self.kwargs['path']
fullfilename = cg.get_fullfilename(os.path.join(path, upfile.name))
destination = None
try: # We're not using "with" because we want to show errors
destination = open(force_str(fullfilename), 'wb')
for chunk in upfile.chunks():
destination.write(chunk)
messages.add_message(
request, messages.SUCCESS,
_('File {} has been uploaded successfully.')
.format(upfile.name))
except IOError as err:
messages.add_message(
request, messages.ERROR,
_('Could not upload file {filename}: {error}').format(
filename=upfile.name,
error=err))
finally:
if destination:
destination.close()
return self.get(self.request)
示例2: get_data
def get_data(self):
# Gather our instances
try:
instances = api.server_list(self.request)
except:
instances = []
exceptions.handle(self.request,
_('Unable to retrieve instances.'))
# Gather our flavors and correlate our instances to them
if instances:
try:
flavors = api.flavor_list(self.request)
except:
flavors = []
exceptions.handle(self.request, ignore=True)
full_flavors = SortedDict([(str(flavor.id), flavor)
for flavor in flavors])
# Loop through instances to get flavor info.
for instance in instances:
try:
flavor_id = instance.flavor["id"]
if flavor_id in full_flavors:
instance.full_flavor = full_flavors[flavor_id]
else:
# If the flavor_id is not in full_flavors list,
# get it via nova api.
instance.full_flavor = api.flavor_get(self.request,
flavor_id)
except:
msg = _('Unable to retrieve instance size information.')
exceptions.handle(self.request, msg)
return instances
示例3: clean
def clean(self):
self.handle_deleted_and_added_contributions()
super().clean()
found_contributor = set()
count_responsible = 0
for form in self.forms:
if not form.cleaned_data or form.cleaned_data.get('DELETE'):
continue
contributor = form.cleaned_data.get('contributor')
if contributor is None:
raise forms.ValidationError(_('Please select the name of each added contributor. Remove empty rows if necessary.'))
if contributor and contributor in found_contributor:
raise forms.ValidationError(_('Duplicate contributor found. Each contributor should only be used once.'))
elif contributor:
found_contributor.add(contributor)
if form.cleaned_data.get('responsibility') == 'RESPONSIBLE':
count_responsible += 1
if count_responsible < 1:
raise forms.ValidationError(_('No responsible contributor found. Each course must have exactly one responsible contributor.'))
elif count_responsible > 1:
raise forms.ValidationError(_('Too many responsible contributors found. Each course must have exactly one responsible contributor.'))
示例4: dump_module_extensions
def dump_module_extensions(course, unit):
"""
Dumps data about students with due date extensions for a particular module,
specified by 'url', in a particular course.
"""
data = []
header = [_("Username"), _("Full Name"), _("Extended Due Date")]
query = StudentFieldOverride.objects.filter(
course_id=course.id,
location=unit.location,
field='due')
for override in query:
due = DATE_FIELD.from_json(json.loads(override.value))
due = due.strftime("%Y-%m-%d %H:%M")
fullname = override.student.profile.name
data.append(dict(zip(
header,
(override.student.username, fullname, due))))
data.sort(key=lambda x: x[header[0]])
return {
"header": header,
"title": _("Users with due date extensions for {0}").format(
title_or_url(unit)),
"data": data
}
示例5: handle
def handle(self, request, data):
domain = api.keystone.get_default_domain(self.request)
try:
LOG.info('Creating user with name "%s"' % data['name'])
if "email" in data:
data['email'] = data['email'] or None
new_user = api.keystone.user_create(request,
name=data['name'],
email=data['email'],
password=data['password'],
project=data['project'],
enabled=True,
domain=domain.id)
messages.success(request,
_('User "%s" was successfully created.')
% data['name'])
if data['project'] and data['role_id']:
roles = api.keystone.roles_for_user(request,
new_user.id,
data['project']) or []
assigned = [role for role in roles if role.id == str(
data['role_id'])]
if not assigned:
try:
api.keystone.add_tenant_user_role(request,
data['project'],
new_user.id,
data['role_id'])
except Exception:
exceptions.handle(request,
_('Unable to add user '
'to primary project.'))
return new_user
except Exception:
exceptions.handle(request, _('Unable to create user.'))
示例6: clean_shipping_absolute
def clean_shipping_absolute(self):
if not self.value:
raise ValidationError(_("A discount value is required"))
if self.range:
raise ValidationError(_("No range should be selected as this benefit does not " "apply to products"))
if self.max_affected_items:
raise ValidationError(_("Shipping discounts don't require a 'max affected items' " "attribute"))
示例7: merge_path
def merge_path(request):
"""
Path merging view
"""
response = {}
if request.method == 'POST':
try:
ids_path_merge = request.POST.getlist('path[]')
if len(ids_path_merge) == 2:
path_a = Path.objects.get(pk=ids_path_merge[0])
path_b = Path.objects.get(pk=ids_path_merge[1])
if not path_a.same_structure(request.user) or not path_b.same_structure(request.user):
response = {'error': _(u"You don't have the right to change these paths")}
elif path_a.merge_path(path_b):
response = {'success': _(u"Paths merged successfully")}
messages.success(request, _(u"Paths merged successfully"))
else:
response = {'error': _(u"No matching points to merge paths found")}
else:
raise
except Exception as exc:
response = {'error': exc, }
return HttpResponse(json.dumps(response), mimetype="application/json")
示例8: confirm
def confirm(self, ok_func, *msgs):
"""Execute the specified callable `ok_func` after the user has
confirmed the specified message.
The confirmation message may be specified as a series of
positional arguments which will be concatenated to a single
prompt.
The callable will be called with a single positional argument
which will be the action request that confirmed the
message. In a web context this will be another object than
this one.
In a non-interactive environment the `ok_func` function is
called directly (i.e. we don't ask any confirmation and act as
confirmation had been given).
"""
cb = self.add_callback(*msgs)
def noop(ar):
return ar.success(_("Aborted"))
cb.add_choice('yes', ok_func, _("Yes"))
cb.add_choice('no', noop, _("No"))
self.set_callback(cb)
if not self.renderer.is_interactive:
if self._confirm_answer:
ok_func(self)
示例9: select_variant_from_properties
def select_variant_from_properties(request):
"""
This is called via an ajax call if the combination of properties are
changed.
"""
product_id = request.POST.get("product_id")
try:
variant = Product.objects.get(pk=product_id)
except Product.DoesNotExist:
return HttpResponse("")
else:
product = variant.parent
options = lfs_utils.parse_properties(request)
variant = product.get_variant(options)
if variant is None:
msg = _(u"The choosen combination of properties is not deliverable.")
variant = product.get_default_variant()
else:
msg = _(u"The product has been changed according to your selection.")
result = simplejson.dumps({
"product": product_inline(request, variant),
"message": msg,
}, cls=LazyEncoder)
return HttpResponse(result, mimetype='application/json')
示例10: get_human_hour
def get_human_hour(self):
if self.scrub_hour == '*':
return _(u'Every hour')
elif self.scrub_hour.startswith('*/'):
return _(u'Every {0} hour(s)').format(self.scrub_hour.split('*/')[1])
else:
return self.scrub_hour
示例11: get_human_daymonth
def get_human_daymonth(self):
if self.scrub_daymonth == '*':
return _(u'Everyday')
elif self.scrub_daymonth.startswith('*/'):
return _(u'Every {0} days').format(self.scrub_daymonth.split('*/')[1])
else:
return self.scrub_daymonth
示例12: get_human_minute
def get_human_minute(self):
if self.scrub_minute == '*':
return _(u'Every minute')
elif self.scrub_minute.startswith('*/'):
return _(u'Every {0} minute(s)').format(self.scrub_minute.split('*/')[1])
else:
return self.scrub_minute
示例13: __init__
def __init__(self, path, raw_file_url=None, username=None, password=None,
local_site_name=None):
if not is_exe_in_path('git'):
# This is technically not the right kind of error, but it's the
# pattern we use with all the other tools.
raise ImportError
self.path = self._normalize_git_url(path)
self.raw_file_url = raw_file_url
self.username = username
self.password = password
self.local_site_name = local_site_name
self.git_dir = None
url_parts = urlparse.urlparse(self.path)
if url_parts[0] == 'file':
self.git_dir = url_parts[2]
p = self._run_git(['--git-dir=%s' % self.git_dir, 'config',
'core.repositoryformatversion'])
failure = p.wait()
if failure:
# See if we have a permissions error
if not os.access(self.git_dir, os.R_OK):
raise SCMError(_("Permission denied accessing the local "
"Git repository '%s'") % self.git_dir)
else:
raise SCMError(_('Unable to retrieve information from '
'local Git repository'))
示例14: video_handler
def video_handler(request, video, format="mp4", prev=None, next=None):
if not video["available"]:
if request.is_admin:
# TODO(bcipolli): add a link, with querystring args that auto-checks this video in the topic tree
messages.warning(request, _("This video was not found! You can download it by going to the Update page."))
elif request.is_logged_in:
messages.warning(request, _("This video was not found! Please contact your teacher or an admin to have it downloaded."))
elif not request.is_logged_in:
messages.warning(request, _("This video was not found! You must login as an admin/teacher to download the video."))
# Fallback mechanism
available_urls = dict([(lang, avail) for lang, avail in video["availability"].iteritems() if avail["on_disk"]])
if video["available"] and not available_urls:
vid_lang = "en"
messages.success(request, "Got video content from %s" % video["availability"]["en"]["stream"])
else:
vid_lang = select_best_available_language(request.language, available_codes=available_urls.keys())
context = {
"video": video,
"title": video["title"],
"selected_language": vid_lang,
"video_urls": video["availability"].get(vid_lang),
"subtitle_urls": video["availability"].get(vid_lang, {}).get("subtitles"),
"prev": prev,
"next": next,
"backup_vids_available": bool(settings.BACKUP_VIDEO_SOURCE),
"use_mplayer": settings.USE_MPLAYER and is_loopback_connection(request),
}
return context
示例15: get_visibility_errors
def get_visibility_errors(self, customer):
if self.product.deleted:
yield ValidationError(_('This product has been deleted.'), code="product_deleted")
if customer and customer.is_all_seeing: # None of the further conditions matter for omniscient customers.
return
if not self.visible:
yield ValidationError(_('This product is not visible.'), code="product_not_visible")
is_logged_in = (bool(customer) and not customer.is_anonymous)
if not is_logged_in and self.visibility_limit != ProductVisibility.VISIBLE_TO_ALL:
yield ValidationError(
_('The Product is invisible to users not logged in.'),
code="product_not_visible_to_anonymous")
if is_logged_in and self.visibility_limit == ProductVisibility.VISIBLE_TO_GROUPS:
# TODO: Optimization
user_groups = set(customer.groups.all().values_list("pk", flat=True))
my_groups = set(self.visibility_groups.values_list("pk", flat=True))
if not bool(user_groups & my_groups):
yield ValidationError(
_('This product is not visible to your group.'),
code="product_not_visible_to_group"
)
for receiver, response in get_visibility_errors.send(ShopProduct, shop_product=self, customer=customer):
for error in response:
yield error