Python django.utils.translation.ugettext_lazy() Examples

The following are code examples for showing how to use django.utils.translation.ugettext_lazy(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: socialhome   Author: jaywink   File: tasks.py    (GNU Affero General Public License v3.0) View Source Project 28 votes vote down vote up
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),
    ) 
Example 2
Project: Bitpoll   Author: fsinfuhh   File: models.py    (GNU General Public License v3.0) View Source Project 9 votes vote down vote up
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))
            ) 
Example 3
Project: Bitpoll   Author: fsinfuhh   File: views.py    (GNU General Public License v3.0) View Source Project 8 votes vote down vote up
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,
    }) 
Example 4
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 5
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 6
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 7
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 8
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 9
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 10
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 11
Project: django-codenerix-products   Author: centrologic   File: models.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 12
Project: django-codenerix-products   Author: centrologic   File: models.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 13
Project: django-codenerix-products   Author: centrologic   File: models.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 14
Project: django-codenerix-products   Author: centrologic   File: models.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 15
Project: django-codenerix-products   Author: centrologic   File: models.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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) 
Example 16
Project: wagtail-sharing   Author: cfpb   File: wagtail_hooks.py    (license) View Source Project 6 votes vote down vote up
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
        ) 
Example 17
Project: Bitpoll   Author: fsinfuhh   File: forms.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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) 
Example 18
Project: Bitpoll   Author: fsinfuhh   File: models.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 19
Project: Bitpoll   Author: fsinfuhh   File: models.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 20
Project: Bitpoll   Author: fsinfuhh   File: views.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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') 
Example 21
Project: Bitpoll   Author: fsinfuhh   File: views.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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) 
Example 22
Project: openbare   Author: openbare   File: models.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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() 
Example 23
Project: parkkihubi   Author: City-of-Helsinki   File: parking.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 24
Project: mos-horizon   Author: Mirantis   File: swift.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 25
Project: mos-horizon   Author: Mirantis   File: ceilometer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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"),
            }),
        ]) 
Example 26
Project: mos-horizon   Author: Mirantis   File: ceilometer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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"),
            }),
        ]) 
Example 27
Project: mos-horizon   Author: Mirantis   File: nova.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 _("-") 
Example 28
Project: mos-horizon   Author: Mirantis   File: nova.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 29
Project: mos-horizon   Author: Mirantis   File: nova.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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) 
Example 30
Project: mos-horizon   Author: Mirantis   File: nova.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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 
Example 31
Project: mos-horizon   Author: Mirantis   File: views.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def object_download(request, container_name, object_path):
    try:
        obj = api.swift.swift_get_object(request, container_name, object_path,
                                         resp_chunk_size=swift.CHUNK_SIZE)
    except Exception:
        redirect = reverse("horizon:project:containers:index")
        exceptions.handle(request,
                          _("Unable to retrieve object."),
                          redirect=redirect)
    # Add the original file extension back on if it wasn't preserved in the
    # name given to the object.
    filename = object_path.rsplit(swift.FOLDER_DELIMITER)[-1]
    if not os.path.splitext(obj.name)[1] and obj.orig_name:
        name, ext = os.path.splitext(obj.orig_name)
        filename = "%s%s" % (filename, ext)
    response = http.StreamingHttpResponse(obj.data)
    safe_name = filename.replace(",", "")
    if six.PY2:
        safe_name = safe_name.encode('utf-8')
    response['Content-Disposition'] = 'attachment; filename="%s"' % safe_name
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Length'] = obj.bytes
    return response 
Example 32
Project: mos-horizon   Author: Mirantis   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def handle(self, request, data):
        try:
            if not data['parent']:
                is_public = data["access"] == "public"
                metadata = ({'is_public': is_public})
                # Create a container
                api.swift.swift_create_container(request,
                                                 data["name"],
                                                 metadata=metadata)
                messages.success(request, _("Container created successfully."))
            else:
                # Create a pseudo-folder
                container, slash, remainder = data['parent'].partition("/")
                remainder = remainder.rstrip("/")
                subfolder_name = "/".join([bit for bit
                                           in (remainder, data['name'])
                                           if bit])
                api.swift.swift_create_subfolder(request,
                                                 container,
                                                 subfolder_name)
                messages.success(request, _("Folder created successfully."))
            return True
        except Exception:
            exceptions.handle(request, _('Unable to create container.')) 
Example 33
Project: mos-horizon   Author: Mirantis   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def handle(self, request, data):
        object_file = self.files.get('object_file')
        if object_file:
            object_path = self._set_object_path(data)
            try:
                obj = api.swift.swift_upload_object(request,
                                                    data['container_name'],
                                                    object_path,
                                                    object_file)
                messages.success(
                    request, _("Object was successfully updated."))
                return obj
            except Exception:
                exceptions.handle(request, _("Unable to update object."))
                return False
        else:
            # If object file is not provided, then a POST method is needed
            # to update ONLY metadata. This must be implemented when
            # object metadata can be updated from this panel.
            return True 
Example 34
Project: mos-horizon   Author: Mirantis   File: views.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_data(self):
        try:
            volume_id = self.kwargs['volume_id']
            volume = cinder.volume_get(self.request, volume_id)
            snapshots = cinder.volume_snapshot_list(
                self.request, search_opts={'volume_id': volume.id})
            if snapshots:
                setattr(volume, 'has_snapshot', True)
            for att in volume.attachments:
                att['instance'] = api.nova.server_get(self.request,
                                                      att['server_id'])
        except Exception:
            redirect = self.get_redirect_url()
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=redirect)
        return volume 
Example 35
Project: mos-horizon   Author: Mirantis   File: views.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _get_volume_types(self):
        try:
            volume_types = cinder.volume_type_list(self.request)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve volume type list.'))

        # check if we have default volume type so we can present the
        # description of no volume type differently
        no_type_description = None
        if self.default_vol_type is None:
            message = \
                _("If \"No volume type\" is selected, the volume will be "
                  "created without a volume type.")

            no_type_description = encoding.force_text(message)

        type_descriptions = [{'name': 'no_type',
                              'description': no_type_description}] + \
                            [{'name': type.name,
                              'description': getattr(type, "description", "")}
                             for type in volume_types]

        return json.dumps(type_descriptions) 
Example 36
Project: mos-horizon   Author: Mirantis   File: views.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(CreateSnapshotView, self).get_context_data(**kwargs)
        context['volume_id'] = self.kwargs['volume_id']
        args = (self.kwargs['volume_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        try:
            volume = cinder.volume_get(self.request, context['volume_id'])
            if (volume.status == 'in-use'):
                context['attached'] = True
                context['form'].set_warning(_("This volume is currently "
                                              "attached to an instance. "
                                              "In some cases, creating a "
                                              "snapshot from an attached "
                                              "volume can result in a "
                                              "corrupted snapshot."))
            context['usages'] = quotas.tenant_limit_usages(self.request)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve volume information.'))
        return context 
Example 37
Project: mos-horizon   Author: Mirantis   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def prepare_source_fields_if_snapshot_specified(self, request):
        try:
            snapshot = self.get_snapshot(request,
                                         request.GET["snapshot_id"])
            self.fields['name'].initial = snapshot.name
            self.fields['size'].initial = snapshot.size
            self.fields['snapshot_source'].choices = ((snapshot.id,
                                                       snapshot),)
            try:
                # Set the volume type from the original volume
                orig_volume = cinder.volume_get(request,
                                                snapshot.volume_id)
                self.fields['type'].initial = orig_volume.volume_type
            except Exception:
                pass
            self.fields['size'].help_text = (
                _('Volume size must be equal to or greater than the '
                  'snapshot size (%sGiB)') % snapshot.size)
            del self.fields['image_source']
            del self.fields['volume_source']
            del self.fields['volume_source_type']
            del self.fields['availability_zone']
        except Exception:
            exceptions.handle(request,
                              _('Unable to load the specified snapshot.')) 
Example 38
Project: mos-horizon   Author: Mirantis   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def prepare_source_fields_if_volume_specified(self, request):
        self.fields['availability_zone'].choices = \
            availability_zones(request)
        volume = None
        try:
            volume = self.get_volume(request, request.GET["volume_id"])
        except Exception:
            msg = _('Unable to load the specified volume. %s')
            exceptions.handle(request, msg % request.GET['volume_id'])

        if volume is not None:
            self.fields['name'].initial = volume.name
            self.fields['description'].initial = volume.description
            min_vol_size = volume.size
            size_help_text = (_('Volume size must be equal to or greater '
                                'than the origin volume size (%sGiB)')
                              % volume.size)
            self.fields['size'].initial = min_vol_size
            self.fields['size'].help_text = size_help_text
            self.fields['volume_source'].choices = ((volume.id, volume),)
            self.fields['type'].initial = volume.type
            del self.fields['snapshot_source']
            del self.fields['image_source']
            del self.fields['volume_source_type'] 
Example 39
Project: mos-horizon   Author: Mirantis   File: forms.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        volume_types = cinder.volume_type_list(request)
        self.fields['type'].choices = [("no_type", _("No volume type"))] + \
                                      [(type.name, type.name)
                                       for type in volume_types]
        if 'initial' in kwargs and 'type' in kwargs['initial']:
            # if there is a default volume type to select, then remove
            # the first ""No volume type" entry
            self.fields['type'].choices.pop(0)

        if "snapshot_id" in request.GET:
            self.prepare_source_fields_if_snapshot_specified(request)
        elif 'image_id' in request.GET:
            self.prepare_source_fields_if_image_specified(request)
        elif 'volume_id' in request.GET:
            self.prepare_source_fields_if_volume_specified(request)
        else:
            self.prepare_source_fields_default(request) 
Example 40
Project: socialhome   Author: jaywink   File: tasks.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def send_follow_notification(follower_id, followed_id):
    """Super simple you've been followed notification to a user."""
    if settings.DEBUG:
        return
    try:
        user = User.objects.get(profile__id=followed_id, is_active=True)
    except User.DoesNotExist:
        logger.warning("No active user with profile %s found for follow notification", followed_id)
        return
    try:
        follower = Profile.objects.get(id=follower_id)
    except Profile.DoesNotExist:
        logger.warning("No follower profile %s found for follow notifications", follower_id)
        return
    logger.info("send_follow_notification - Sending mail to %s", user.email)
    subject = _("New follower: %s" % follower.handle)
    context = get_common_context()
    context.update({
        "subject": subject, "actor_name": follower.name_or_handle,
        "actor_url": "%s%s" % (settings.SOCIALHOME_URL, follower.get_absolute_url()),
        "name": user.profile.name_or_handle,
    })
    send_mail(
        "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
        render_to_string("notifications/follow.txt", context=context),
        settings.DEFAULT_FROM_EMAIL,
        [user.email],
        fail_silently=False,
        html_message=render_to_string("notifications/follow.html", context=context),
    ) 
Example 41
Project: socialhome   Author: jaywink   File: tasks.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def send_reply_notifications(content_id):
    """Super simple reply notification to content local participants.

    Until proper notifications is supported, just pop out an email.
    """
    if settings.DEBUG:
        return
    try:
        content = Content.objects.get(id=content_id, content_type=ContentType.REPLY)
    except Content.DoesNotExist:
        logger.warning("No reply content found with id %s", content_id)
        return
    root_content = content.root
    exclude_user = content.author.user if content.local else None
    participants = get_root_content_participants(root_content, exclude_user=exclude_user)
    if not participants:
        return
    subject = _("New reply to: %s" % root_content.short_text_inline)
    # TODO use fragment url to reply directly when available
    content_url = "%s%s" % (settings.SOCIALHOME_URL, root_content.get_absolute_url())
    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()),
        "reply_text": content.text, "reply_rendered": content.rendered, "reply_url": content_url,
    })
    for participant in participants:
        context["name"] = participant.profile.name_or_handle
        logger.info("send_reply_notifications - Sending mail to %s", participant.email)
        send_mail(
            "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
            render_to_string("notifications/reply.txt", context=context),
            settings.DEFAULT_FROM_EMAIL,
            [participant.email],
            fail_silently=False,
            html_message=render_to_string("notifications/reply.html", context=context),
        ) 
Example 42
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['name', 6],
                ['tax', 3],
                ['default', 3],
                ['recargo_equivalencia', 4],

            )
        ]
        return g 
Example 43
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups_details__():
        g = [
            (
                _('Details'), 12,
                ['name', 6],
                ['tax', 3],
                ['default', 3],
                ['recargo_equivalencia', 4],
            )
        ]
        return g 
Example 44
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def clean(self):
        cleaned_data = super(FeatureForm, self).clean()
        type_value = cleaned_data.get("type_value")
        list_value = cleaned_data.get("list_value")

        if type_value == TYPE_VALUES[2][0] and list_value is None:
            self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")]) 
Example 45
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def clean(self):
        cleaned_data = super(FeatureSpecialForm, self).clean()
        type_value = cleaned_data.get("type_value")
        list_value = cleaned_data.get("list_value")

        if type_value == TYPE_VALUES[2][0] and list_value is None:
            self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")]) 
Example 46
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['order', 2],
                ['code', 4],
                ['public', 3],
                ['show_menu', 3],
                ['icon', 6],
                ['image', 6],
            )
        ]
        return g 
Example 47
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['order', 2],
                ['code', 2],
                ['family', 4],
                ['public', 1],
                ['show_menu', 1],
                ['show_only_product_stock', 2],
                ['icon', 6],
                ['image', 6],
            )
        ]
        return g 
Example 48
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups_details__():
        g = [
            (
                _('Details'), 12,
                ['order', 2],
                ['code', 4],
                ['family', 4],
                ['public', 1],
                ['show_menu', 1],
                ['show_only_product_stock', 2],
                ['image', 6],
                ['icon', 6],
            )
        ]
        return g 
Example 49
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['order', 3],
                ['code', 3],
                ['public', 2],
                ['show_menu', 2],
                ['outstanding', 2],
                ['icon', 6],
                ['image', 6],
            )
        ]
        return g 
Example 50
Project: django-codenerix-products   Author: centrologic   File: forms.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['code', 4],
                ['price_base', 4],
                ['public', 1],
                ['of_sales', 1],
                ['of_purchase', 1],
                ['force_stock', 1],
                ['model', 4],
                ['brand', 4],
                ['feature_special', 4],
                ['family', 4],
                ['category', 4],
                ['subcategory', 4],
                ['tax', 4],
                ['url_video', 4],
            ),
            (
                _('Packaging information'), 12,
                ['packing_cost', 4],
                ['weight', 4],
            )
        ]
        return g