Python django.utils.translation.ugettext_lazy() Examples

The following are 30 code examples for showing how to use django.utils.translation.ugettext_lazy(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.translation , or try the search function .

Example 1
Project: openwisp-users   Author: openwisp   File: mixins.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _validate_org_relation(self, rel, field_error='organization'):
        """
        if the relation is owned by a specific organization
        this object must be related to the same organization
        """
        # avoid exceptions caused by the relation not being set
        if not hasattr(self, rel):
            return
        rel = getattr(self, rel)
        if (
            rel
            and rel.organization_id
            and str(self.organization_id) != str(rel.organization_id)
        ):
            message = _(
                'Please ensure that the organization of this {object_label} '
                'and the organization of the related {related_object_label} match.'
            )
            message = message.format(
                object_label=self._meta.verbose_name,
                related_object_label=rel._meta.verbose_name,
            )
            raise ValidationError({field_error: message}) 
Example 2
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def clean(self):
        cd = super(CustomerForm, self).clean()

        phone = cd.get('phone')
        country = cd.get('country')

        if len(phone) < 1:
            return cd

        try:
            phonenumbers.parse(phone, country)
        except phonenumbers.NumberParseException:
            msg = _('Enter a valid phone number')
            self._errors["phone"] = self.error_class([msg])

        return cd 
Example 3
Project: Servo   Author: fpsw   File: checkin.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):

        super(DeviceForm, self).__init__(*args, **kwargs)

        if Configuration.false('checkin_require_password'):
            self.fields['password'].required = False

        if Configuration.true('checkin_require_condition'):
            self.fields['condition'].required = True

        if kwargs.get('instance'):
            prod = gsxws.Product('')
            prod.description = self.instance.description

            if prod.is_ios:
                self.fields['password'].label = _('Passcode')

            if not prod.is_ios:
                del(self.fields['imei'])
            if not prod.is_mac:
                del(self.fields['username'])

        if Configuration.true('checkin_password'):
            self.fields['password'].widget = forms.TextInput(attrs={'class': 'span12'}) 
Example 4
Project: Servo   Author: fpsw   File: notes.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(NoteForm, self).__init__(*args, **kwargs)
        note = kwargs['instance']
        self.fields['sender'] = forms.ChoiceField(
            label=_('From'),
            choices=note.get_sender_choices(),
            widget=forms.Select(attrs={'class': 'span12'})
        )

        self.fields['body'].widget = AutocompleteTextarea(
            rows=20,
            choices=Template.templates()
        )

        if note.order:
            url = reverse('notes-render_template', args=[note.order.pk])
            self.fields['body'].widget.attrs['data-url'] = url 
Example 5
Project: Servo   Author: fpsw   File: repair.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def create_from_gsx(cls, confirmation, order, device, user):
        """Creates a new Repair for order with confirmation number."""
        try:
            repair = cls.objects.get(confirmation=confirmation)
            msg = {'repair': repair.confirmation, 'order': repair.order}
            raise ValueError(_('Repair %(repair)s already exists for order %(order)s') % msg)
        except cls.DoesNotExist:
            pass

        repair = cls(order=order, created_by=user)
        repair.device = device
        repair.confirmation = confirmation
        repair.gsx_account = GsxAccount.default(user, order.queue)
        repair.submitted_at = timezone.now() # RepairDetails doesn't have this!
        repair.save()

        try:
            repair.get_details()
            repair.update_status(user)
        except gsxws.GsxError as e:
            if e.code == 'RPR.LKP.01': # repair not found
                repair.delete()
                raise ValueError(_('Repair %s not found in GSX') % confirmation)

        return repair 
Example 6
Project: Servo   Author: fpsw   File: product.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def sell(self, amount, location):
        """
        Deduct product from inventory with specified location
        """
        if not self.track_inventory():
            return

        try:
            inventory = Inventory.objects.get(product=self, location=location)
            
            try:
                inventory.amount_stocked  = inventory.amount_stocked - amount
                inventory.amount_reserved = inventory.amount_reserved - amount
            except Exception as e:
                # @TODO: Would be nice to trigger a warning
                pass

            inventory.save()
        except Inventory.DoesNotExist:
            raise ValueError(_(u"Product %s not found in inventory.") % self.code) 
Example 7
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def activate_locale(self):
        """
        Activates this user's locale
        """
        try:
            lc = self.locale.split('.')
            region = self.region.split('.')
            locale.setlocale(locale.LC_TIME, region)
            locale.setlocale(locale.LC_MESSAGES, lc)
            locale.setlocale(locale.LC_NUMERIC, region)
            locale.setlocale(locale.LC_MONETARY, region)
        except Exception as e:
            locale.setlocale(locale.LC_ALL, None)

        # Return the language code
        return self.locale.split('_', 1)[0] 
Example 8
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_print_dict(self, kind='confirmation'):
        """
        Return context dict for printing this order
        """
        r = {}
        r['order'] = self
        r['conf'] = Configuration.conf()
        r['title'] = _(u"Service Order #%s") % self.code
        r['notes'] = self.note_set.filter(is_reported=True)

        if kind == 'receipt':
            try:
                # Include the latest invoice data for receipts
                r['invoice'] = self.invoice_set.latest()
            except Exception as e:
                pass

        return r 
Example 9
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def set_location(self, new_location, user):
        """
        Moves order to new location
        """
        # move the products too
        for soi in self.serviceorderitem_set.all():
            product = soi.product

            try:
                source = Inventory.objects.get(location=self.location, product=product)
                source.move(new_location, soi.amount)
            except Inventory.DoesNotExist:
                pass # @TODO: Is this OK?

        self.location = new_location
        msg = _(u"Order %s moved to %s") % (self.code, new_location.title)
        self.notify("set_location", msg, user)
        self.save()

        return msg 
Example 10
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_product(self, product, amount, user):
        """
        Adds this product to the Service Order with stock price
        """
        oi = ServiceOrderItem(order=self, created_by=user)
        oi.product = product
        oi.code = product.code
        oi.title = product.title
        oi.description = product.description
        oi.amount = amount

        oi.price_category = 'stock'
        oi.price = product.price_sales_stock

        oi.save()

        self.notify("product_added", _('Product %s added') % oi.title, user)

        return oi 
Example 11
Project: Servo   Author: fpsw   File: order.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def save(self, *args, **kwargs):

        location = self.created_by.location

        if self.location_id is None:
            self.location = location

        if self.checkin_location is None:
            self.checkin_location = location

        if self.checkout_location is None:
            self.checkout_location = location

        if self.customer and self.customer_name == '':
            self.customer_name = self.customer.fullname

        super(Order, self).save(*args, **kwargs)

        if self.code is None:
            self.url_code = encode_url(self.id).upper()
            self.code = settings.INSTALL_ID + str(self.id).rjust(6, '0')
            event = _('Order %s created') % self.code
            self.notify('created', event, self.created_by)
            self.save() 
Example 12
Project: Servo   Author: fpsw   File: purchases.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def trigger_purchase_order_created(sender, instance, created, **kwargs):

    sales_order = instance.sales_order

    if sales_order is None:
        return

    if not sales_order.is_editable:
        return

    if created:
        msg = _("Purchase Order %d created") % instance.id
        sales_order.notify("po_created", msg, instance.created_by)

    # Trigger status change for GSX repair submit (if defined)
    if instance.submitted_at:
        if sales_order.queue:
            queue = sales_order.queue
            if queue.status_products_ordered:
                # Queue has a status for product_ordered - trigger it
                new_status = queue.status_products_ordered
                sales_order.set_status(new_status, instance.created_by) 
Example 13
Project: Servo   Author: fpsw   File: note.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_sms_builtin(self, recipient, sender=None):
        """
        Sends SMS through built-in gateway
        """
        if not settings.SMS_HTTP_URL:
            raise ValueError(_('System is not configured for built-in SMS support.'))

        if sender is None:
            location = self.created_by.location
            sender = location.title

        data = urllib.urlencode({
            'username'  : settings.SMS_HTTP_USERNAME,
            'password'  : settings.SMS_HTTP_PASSWORD,
            'numberto'  : recipient.replace(' ', ''),
            'numberfrom': sender.encode(SMS_ENCODING),
            'message'   : self.body.encode(SMS_ENCODING),
        })

        from ssl import _create_unverified_context
        f = urllib.urlopen(settings.SMS_HTTP_URL, data, context=_create_unverified_context())
        return f.read() 
Example 14
Project: Servo   Author: fpsw   File: parts.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def update_sn(self):
        # CTS parts not eligible for SN update
        if self.return_status == 'Convert To Stock':
            return

        if not self.repair.confirmation:
            raise ValueError(_('GSX repair has no dispatch ID'))

        product = self.order_item.product

        if not product.is_serialized:
            return

        if product.part_type == "MODULE":
            self.update_module_sn()
        elif product.part_type == "REPLACEMENT":
            self.update_replacement_sn() 
Example 15
Project: django-places   Author: oscarmcm   File: widgets.py    License: MIT License 6 votes vote down vote up
def __init__(self, attrs=None):
        _widgets = (
            widgets.TextInput(
                attrs={'data-geo': 'formatted_address', 'data-id': 'map_place'}
            ),
            widgets.TextInput(
                attrs={
                    'data-geo': 'lat',
                    'data-id': 'map_latitude',
                    'placeholder': _('Latitude'),
                }
            ),
            widgets.TextInput(
                attrs={
                    'data-geo': 'lng',
                    'data-id': 'map_longitude',
                    'placeholder': _('Longitude'),
                }
            ),
        )
        super(PlacesWidget, self).__init__(_widgets, attrs) 
Example 16
Project: openwisp-users   Author: openwisp   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        value = self.name
        if not self.is_active:
            value = '{0} ({1})'.format(value, _('disabled'))
        return value 
Example 17
Project: openwisp-users   Author: openwisp   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean(self):
        if self.organization_user.organization.pk != self.organization.pk:
            raise ValidationError(
                {
                    'organization_user': _(
                        'The selected user is not member of this organization.'
                    )
                }
            ) 
Example 18
Project: openwisp-users   Author: openwisp   File: mixins.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _validate_org_reverse_relation(self, rel_name, field_error='organization'):
        """
        prevents changing organization for existing objects
        which have relations specified by ``rel_name`` pointing to them,
        in order to prevent inconsistencies
        (relations belonging to different organizations)
        """
        # do nothing on new objects, because they
        # cannot have relations pointing to them
        if self._state.adding:
            return
        old_self = self.__class__.objects.get(pk=self.pk)
        old_org = old_self.organization
        # org hasn't been changed, everything ok
        if old_org == self.organization:
            return
        rel = getattr(self, rel_name)
        count = rel.count()
        if count:
            rel_meta = rel.model._meta
            related_label = (
                rel_meta.verbose_name if count == 1 else rel_meta.verbose_name_plural
            )
            verb = _('is') if count == 1 else _('are')
            message = _(
                'The organization of this {object_label} cannot be changed '
                'because {0} {related_object_label} {verb} still '
                'related to it'.format(
                    count,
                    object_label=self._meta.verbose_name,
                    related_object_label=related_label,
                    verb=verb,
                )
            )
            raise ValidationError({field_error: message}) 
Example 19
Project: openwisp-users   Author: openwisp   File: apps.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_receivers(self):
        OrganizationUser = load_model('openwisp_users', 'OrganizationUser')
        OrganizationOwner = load_model('openwisp_users', 'OrganizationOwner')
        signal_tuples = [(post_save, 'post_save'), (post_delete, 'post_delete')]

        for model in [OrganizationUser, OrganizationOwner]:
            for signal, name in signal_tuples:
                signal.connect(
                    self.update_organizations_dict,
                    sender=model,
                    dispatch_uid='{}_{}_update_organizations_dict'.format(
                        name, model.__name__
                    ),
                ) 
Example 20
Project: openwisp-users   Author: openwisp   File: admin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_inactive(self, request, queryset):
        queryset.update(is_active=False)
        count = queryset.count()
        if count:
            self.message_user(
                request,
                _(
                    f'Successfully made {count} '
                    f'{model_ngettext(self.opts, count)} inactive.'
                ),
                messages.SUCCESS,
            ) 
Example 21
Project: openwisp-users   Author: openwisp   File: admin.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_active(self, request, queryset):
        queryset.update(is_active=True)
        count = queryset.count()
        if count:
            self.message_user(
                request,
                _(
                    f'Successfully made {count} '
                    f'{model_ngettext(self.opts, count)} active.'
                ),
                messages.SUCCESS,
            ) 
Example 22
Project: Servo   Author: fpsw   File: devices.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(DeviceSearchForm, self).__init__(*args, **kwargs)
        self.fields['description'] = AutocompleteCharField(
            '/api/device_models/',
            max_length=128,
            required=False,
            label=_('Description contains')
        ) 
Example 23
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        cd = super(CustomerSearchForm, self).clean()

        for k, v in cd.items():
            if v not in ['', None]:
                return cd

        raise forms.ValidationError(_('Please specify at least one parameter')) 
Example 24
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_datafile(self):
        d = self.cleaned_data.get('datafile')
        if not d.content_type.startswith('text'):
            raise forms.ValidationError(_('Data file should be in text format'))
        return d 
Example 25
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        cd = super(ProfileForm, self).clean()

        if cd.get('gsx_password') == "":
            del(cd['gsx_password'])

        cd['tech_id'] = cd['tech_id'].upper()

        if cd.get('password1'):
            if cd['password1'] != cd['password2']:
                raise forms.ValidationError(_("Password and confirmation do not match!"))

        return cd 
Example 26
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save(self, **kwargs):
        users = []
        string = u''
        cd = self.cleaned_data
        data = cd['datafile'].read()

        for i in ('utf-8', 'latin-1',):
            try:
                string = data.decode(i)
            except:
                pass

        if not string:
            raise ValueError(_('Unsupported file encoding'))

        sio = io.StringIO(string, newline=None)

        for l in sio.readlines():
            cols = l.strip().split("\t")
            if len(cols) < 2:
                continue # Skip empty rows

            user = User(username=cols[2])
            user.first_name = cols[0]
            user.last_name = cols[1]
            user.email = cols[3]
            user.set_password(cols[4])
            user.save()

            user.location = cd['location']
            user.timezone = user.location.timezone
            user.groups.add(cd['group'])
            user.queues = cd['queues']
            user.save()

            users.append(user)

        return users 
Example 27
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save(self, **kwargs):
        from django.db.utils import IntegrityError

        try:
            location = super(LocationForm, self).save(**kwargs)
        except IntegrityError:
            msg = _('A location with that name already exists')
            self._errors['title'] = self.error_class([msg])
            raise forms.ValidationError(msg)

        return location 
Example 28
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_order_template(self):
        from servo.lib.utils import file_type
        tpl = self.cleaned_data.get('order_template')

        if tpl is None: # file was not uploaded
            return

        ftype = file_type(tpl.file.read())

        if ftype != 'text/html':
            raise forms.ValidationError(_('Print tempates must be in HTML format'))

        return tpl 
Example 29
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_content(self):
        content = self.cleaned_data.get('content')
        try:
            template.Template(content)
        except template.TemplateSyntaxError, e:
            raise forms.ValidationError(_('Syntax error in template: %s') % e) 
Example 30
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_pct_margin(self, *args, **kwargs):
        margin = self.cleaned_data.get('pct_margin')
        if re.match('^\d[\-=;\d]*\d$', margin):
            return margin

        raise forms.ValidationError(_('Invalid margin format'))