def send_share_notification(share_id):
"""Super simple you're content has been shared notification to a user."""
if settings.DEBUG:
return
try:
content = Content.objects.get(id=share_id, content_type=ContentType.SHARE, share_of__local=True)
except Content.DoesNotExist:
logger.warning("No share content found with id %s", share_id)
return
content_url = "%s%s" % (settings.SOCIALHOME_URL, content.share_of.get_absolute_url())
subject = _("New share of: %s" % content.share_of.short_text_inline)
context = get_common_context()
context.update({
"subject": subject, "actor_name": content.author.name_or_handle,
"actor_url": "%s%s" % (settings.SOCIALHOME_URL, content.author.get_absolute_url()),
"content_url": content_url, "name": content.share_of.author.name_or_handle,
})
send_mail(
"%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
render_to_string("notifications/share.txt", context=context),
settings.DEFAULT_FROM_EMAIL,
[content.share_of.author.user.email],
fail_silently=False,
html_message=render_to_string("notifications/share.html", context=context),
)
python类ugettext_lazy()的实例源码
def send(self, request):
if (not self.last_email) or self.last_email + timedelta(hours=12) < now(): # TODO: TIMEDELTA mit config
old_lang = translation.get_language()
translation.activate(self.user.language)
link = reverse('poll_vote', args=(self.poll.url,)) # TODO: hier direkt das poll oder das Vote?
email_content = render_to_string('invitations/mail_invite.txt', {
'receiver': self.user.username,
'creator': self.creator.username,
'link': link
})
try:
send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email])
self.last_email = now()
self.save()
except SMTPRecipientsRefused:
translation.activate(old_lang)
messages.error(
request, _("The mail server had an error sending the notification to {}".format(self.user.username))
)
translation.activate(old_lang)
else:
messages.error(
request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username))
)
def create(request):
error = None
group_name = ''
if request.method == 'POST':
group_name = request.POST.get('group_name', '')
try:
create_usergroup(request.user, group_name)
msg = _('Group "{0}" was created.').format(group_name)
messages.success(request, msg)
return redirect('groups_show', group_name)
except GroupError as e:
error = e.message
return TemplateResponse(request, 'groups/create.html', {
'error': error,
'group_name': group_name,
})
def __groups__(self):
g = [
(
_('Details'), 12,
['family', 3],
['category', 3],
['order', 3],
['public', 3],
['type_price', 3],
['price', 3],
['type_value', 3],
['list_value', 3],
['image', 6],
)
]
return g
def __groups__(self):
g = [
(
_('Details'), 12,
['family', 3],
['category', 3],
['order', 3],
['public', 3],
['type_price', 3],
['price', 3],
['type_value', 3],
['list_value', 3],
['image', 6],
['attribute', 6],
)
]
return g
def __groups__(self):
g = [
(
_('Details'), 12,
['family', 3],
['category', 3],
['order', 2],
['public', 2],
['unique', 2],
['type_price', 3],
['price', 3],
['type_value', 3],
['list_value', 3],
['image', 6],
)
]
return g
def __groups__(self):
g = [
(
_('Details'), 12,
['order', 2],
['code', 3],
['category', 3],
['public', 1],
['show_menu', 1],
['show_brand', 1],
['outstanding', 1],
['icon', 6],
['image', 6],
)
]
return g
def __groups_details__():
g = [
(
_('Details'), 12,
['order', 2],
['code', 3],
['category', 3],
['public', 1],
['show_menu', 1],
['show_brand', 1],
['outstanding', 1],
['icon', 6],
['image', 6],
)
]
return g
def __groups__(self):
g = [(
_('Details'), 12,
["product", 4],
["offer", 2],
["outstanding", 2],
['most_sold', 2],
["sample", 2],
["code", 4],
["price_base_local", 4],
["ean13", 4],
["related", 6],
["related_accesory", 6],
), (
_('Packaging information'), 12,
['packing_cost', 4],
['weight', 4],
)]
return g
def __groups__(self):
g = [(
_('Details'), 12,
["offer", 3],
["outstanding", 3],
['most_sold', 3],
["sample", 3],
["code", 4],
["price_base_local", 4],
["ean13", 4],
["related", 6],
["related_accesory", 6],
), (
_('Packaging information'), 12,
['packing_cost', 4],
['weight', 4],
)]
return g
def lock_delete(self):
if self.products.exists():
return _("Cannot delete family model, relationship between family model and products")
elif self.features.exists():
return _("Cannot delete family model, relationship between family model and features")
elif self.attributes.exists():
return _("Cannot delete family model, relationship between family model and attributes")
elif self.feature_specials.exists():
return _("Cannot delete family model, relationship between family model and feature special")
elif self.categories.exists():
return _("Cannot delete family model, relationship between family model and categories")
else:
return super(Family, self).lock_delete()
# categorias
def lock_delete(self):
if self.products.exists():
return _("Cannot delete category model, relationship between category model and products")
elif self.features.exists():
return _("Cannot delete category model, relationship between category model and features")
elif self.attributes.exists():
return _("Cannot delete category model, relationship between category model and attributes")
elif self.feature_specials.exists():
return _("Cannot delete category model, relationship between category model and feature special")
elif self.subcategory.exists():
return _("Cannot delete category model, relationship between category model and subcategories")
else:
return super(Category, self).lock_delete()
# subcategorias
def __fields__(self, info):
lang = get_language_database()
fields = []
fields.append(('family__{}__name'.format(lang), _("Family")))
fields.append(('category__{}__name'.format(lang), _("Category")))
fields.append(('subcategory__{}__name'.format(lang), _("Subcategory")))
fields.append(('public', _("Public")))
fields.append(('tax', _("Tax")))
fields.append(('code', _("Code")))
fields.append(('price_base', _("Price base")))
fields.append(('of_sales', _("Sales")))
fields.append(('of_purchase', _("Purchase")))
fields.append(('force_stock', _("Force stock")))
fields.append(('url_video', _("Url Video")))
fields.append(('feature_special', _("Feature special")))
fields.append(('packing_cost', _("Packing cost")))
fields.append(('weight', _("Weight")))
return fields
def __fields__(self, info):
lang = get_language_database()
fields = []
fields.append(('code', _("Code")))
fields.append(('product__code', _("Product Code")))
fields.append(('{}__name'.format(lang), _("Product")))
fields.append(('product__family__{}__name'.format(lang), _("Family")))
fields.append(('product__category__{}__name'.format(lang), _("Category")))
fields.append(('product__subcategory__{}__name'.format(lang), _("Subcategory")))
fields.append(('{}__public'.format(lang), _("Public")))
fields.append(('stock_real', _("Stock real")))
fields.append(('stock_lock', _("Stock lock")))
fields.append(('price', _("Price")))
fields.append(('is_pack', _("Is pack")))
fields.append(('sample', _("Sample")))
return fields
def save(self, *args, **kwargs):
product_final = ProductFinal.objects.filter(pk=self.product_final_id).first()
# se comprueba que no se repite el valor de las caracteristicas especiales de los productos finales cuando sean unicas
if product_final:
if product_final.product.feature_special and product_final.product.feature_special.unique:
if ProductUnique.objects.filter(
value=self.value,
product_final__product=product_final.product
).exists():
raise ValidationError(_('Ya existe un producto final con el valor de la caracteristicas especial'))
else:
raise ValidationError(_("Product don't seleted"))
# save and update stock of product final
with transaction.atomic():
r = super(ProductUnique, self).save(*args, **kwargs)
product_final.stock_real = ProductUnique.objects.filter(product_final=product_final).aggregate(stock=Sum('stock_real'))['stock']
product_final.save()
return r
# producto estrella (solo un registro publico)
def add_sharing_link(page, page_perms, is_parent=False):
sharing_url = get_sharing_url(page)
if sharing_url:
if hasattr(page, 'get_admin_display_title'):
title = page.get_admin_display_title()
else:
title = page.title
yield wagtailadmin_widgets.Button(
'View sharing link',
sharing_url,
attrs={
'title': _("View shared revision of '{}'").format(title),
},
priority=90
)
def clean_invitees(self):
self.invitee_users = []
data = self.cleaned_data['invitees']
invitees = [s.strip() for s in data.split(',')]
for invitee in invitees:
User = get_user_model()
try:
invitee_user = User.objects.get(username=invitee)
self.invitee_users.append(invitee_user)
except User.DoesNotExist:
raise forms.ValidationError(_('There is no user "%s."')
% invitee)
has_invitation = bool(GroupInvitation.objects.filter(
group=self.group, invitee=invitee_user))
if has_invitation:
raise forms.ValidationError(
_('"%s" already has an invitation.') % invitee)
already_member = \
invitee_user.groups.filter(name=self.group.name).exists()
if already_member:
raise forms.ValidationError(
_('"%s" is already a member of this group.')
% invitee)
def create_usergroup(user, name):
if not _group_name_re.match(name):
raise GroupError(_('Invalid group name.'))
if len(name) < MIN_GROUPNAME_LENGTH:
err_msg = _('The group name must be at least {} characters').format(
MIN_GROUPNAME_LENGTH)
raise GroupError(err_msg)
if Group.objects.filter(name__iexact=name).count():
raise GroupError(_('Group does already exist.'))
group = Group.objects.create(name=name)
group_proxy = GroupProxy(group)
group_proxy.add_member(user)
group.properties.admins.add(user)
return group
def can_vote(self, user: BitpollUser, request: HttpRequest, is_edit: bool=False) -> bool:
"""
Determine if the user is allowed to vote
:param is_edit: if the vote is an edit
:param user:
:param request:
:return:
"""
has_voted = self.has_voted(user)
if self.one_vote_per_user and has_voted and not is_edit:
messages.error(request, _("It is only one vote allowed. You have already voted."))
return False
elif self.require_login and not user.is_authenticated:
messages.error(request, _("Login required to vote."))
return False
elif self.require_invitation and (not user.is_authenticated or user not in self.invitation_set.all().values('user')):
messages.error(request, _("You are not allowed to vote in this poll. You have to be invited"))
return False
return True
def change_email(request, token):
try:
data = signing.loads(token, max_age=TOKEN_MAX_AGE)
except signing.SignatureExpired:
return TemplateResponse(request, 'registration/token_expired.html')
except signing.BadSignature:
return TemplateResponse(request, 'registration/token_invalid.html')
if request.user.username != data.get('username'):
return TemplateResponse(request, 'registration/token_invalid.html')
email = data.get('email')
try:
validate_email(email)
except ValidationError:
return TemplateResponse(request, 'registration/token_invalid.html')
request.user.email = email
request.user.save()
messages.success(request, _('Your email address has been changed.'))
return redirect('registration_account')
def _send_mail_or_error_page(subject, content, address, request):
try:
send_mail(subject, content, None, [address])
if settings.DEBUG:
print(u"VALIDATION MAIL to {0}\nSubject: {1}\n{2}".format(
address, subject, content))
except SMTPRecipientsRefused as e:
wrong_email, (error_code, error_msg) = e.recipients.items()[0]
unknown = 'User unknown' in error_msg
if not unknown:
error_email_content = u'{0}: {1}'.format(e.__class__.__name__,
repr(e.recipients))
send_mail(
_('Registration: Sending mail failed: {}'.format(address)),
error_email_content,
None,
[settings.TEAM_EMAIL])
return TemplateResponse(request, 'registration/email_error.html', {
'unknown': unknown,
'error_code': error_code,
'error_msg': error_msg,
'recipient': wrong_email
})
return redirect('registration_request_successful', address)
def renew(self):
"""Renew lendable.
If renewals are available update the due_on date by adding
another period equal to lending_period_in_days.
If no renewals available raise error and display message to user.
"""
if self.renewals > 0:
self.renewals -= 1
self.due_on = self.due_on + timedelta(self.lending_period_in_days)
else:
raise ValidationError(
_("No more renewals are available for this item.")
)
return self.save()
def validate(self, data):
if self.instance and (now() - self.instance.created_at) > settings.PARKKIHUBI_TIME_PARKINGS_EDITABLE:
if set(data.keys()) != {'time_end'}:
raise ParkingException(
_('Grace period has passed. Only "time_end" can be updated via PATCH.'),
code='grace_period_over',
)
if self.instance:
# a partial update might be missing one or both of the time fields
time_start = data.get('time_start', self.instance.time_start)
time_end = data.get('time_end', self.instance.time_end)
else:
time_start = data['time_start']
time_end = data['time_end']
if time_end is not None and time_start > time_end:
raise serializers.ValidationError(_('"time_start" cannot be after "time_end".'))
return data
def swift_delete_object(request, container_name, object_name):
objects, more = swift_get_objects(request, container_name,
prefix=object_name)
# In case the given object is pseudo folder,
# it can be deleted only if it is empty.
# swift_get_objects will return at least
# one object (i.e container_name) even if the
# given pseudo folder is empty. So if swift_get_objects
# returns more than one object then only it will be
# considered as non empty folder.
if len(objects) > 1:
error_msg = _("The pseudo folder cannot be deleted "
"since it is not empty.")
exc = exceptions.Conflict(error_msg)
raise exc
swift_api(request).delete_object(container_name, object_name)
return True
def _get_cinder_meters_info(self):
"""Returns additional info for each meter.
That will be used for augmenting the Ceilometer meter.
"""
# TODO(lsmola) Unless the Ceilometer will provide the information
# below, I need to define it as a static here. I will be joining this
# to info that I am able to obtain from Ceilometer meters, hopefully
# some day it will be supported all.
return OrderedDict([
('volume', {
'label': '',
'description': _("Existence of volume"),
}),
('volume.size', {
'label': '',
'description': _("Size of volume"),
}),
])
def _get_kwapi_meters_info(self):
"""Returns additional info for each meter.
That will be used for augmenting the Ceilometer meter.
"""
# TODO(lsmola) Unless the Ceilometer will provide the information
# below, I need to define it as a static here. I will be joining this
# to info that I am able to obtain from Ceilometer meters, hopefully
# some day it will be supported all.
return OrderedDict([
('energy', {
'label': '',
'description': _("Amount of energy"),
}),
('power', {
'label': '',
'description': _("Power consumption"),
}),
])
def image_name(self):
import glanceclient.exc as glance_exceptions # noqa
from openstack_dashboard.api import glance # noqa
if not self.image:
return _("-")
if hasattr(self.image, 'name'):
return self.image.name
if 'name' in self.image:
return self.image['name']
else:
try:
image = glance.image_get(self.request, self.image['id'])
return image.name
except (glance_exceptions.ClientException,
horizon_exceptions.ServiceCatalogException):
return _("-")
def __str__(self):
if 'name' in self.group:
vals = {'from': self.from_port,
'to': self.to_port,
'ip_protocol': self.ip_protocol,
'group': self.group['name']}
return (_('ALLOW %(from)s:%(to)s/%(ip_protocol)s from %(group)s') %
vals)
else:
vals = {'from': self.from_port,
'to': self.to_port,
'ip_protocol': self.ip_protocol,
'cidr': self.ip_range['cidr']}
return (_('ALLOW %(from)s:%(to)s/%(ip_protocol)s from %(cidr)s') %
vals)
# The following attributes are defined to keep compatibility with Neutron
def rule_create(self, parent_group_id,
direction=None, ethertype=None,
ip_protocol=None, from_port=None, to_port=None,
cidr=None, group_id=None):
# Nova Security Group API does not use direction and ethertype fields.
try:
sg = self.client.security_group_rules.create(parent_group_id,
ip_protocol,
from_port,
to_port,
cidr,
group_id)
except nova_exceptions.BadRequest:
raise horizon_exceptions.Conflict(
_('Security group rule already exists.'))
return SecurityGroupRule(sg)
def evacuate_host(request, host, target=None, on_shared_storage=False):
# TODO(jmolle) This should be change for nova atomic api host_evacuate
hypervisors = novaclient(request).hypervisors.search(host, True)
response = []
err_code = None
for hypervisor in hypervisors:
hyper = Hypervisor(hypervisor)
# if hypervisor doesn't have servers, the attribute is not present
for server in hyper.servers:
try:
novaclient(request).servers.evacuate(server['uuid'],
target,
on_shared_storage)
except nova_exceptions.ClientException as err:
err_code = err.code
msg = _("Name: %(name)s ID: %(uuid)s")
msg = msg % {'name': server['name'], 'uuid': server['uuid']}
response.append(msg)
if err_code:
msg = _('Failed to evacuate instances: %s') % ', '.join(response)
raise nova_exceptions.ClientException(err_code, msg)
return True