django.utils.translation.gettext - python examples

Here are the examples of the python api django.utils.translation.gettext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

50 Examples 7

3 View Complete Implementation : forms.py
Copyright MIT License
Author : vitorfs
    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        is_subscribed = Subscriber.objects.filter(
            email__iexact=email,
            mailing_list=self.mailing_list,
            status=Status.SUBSCRIBED
        )
        if not is_subscribed:
            email_validation_error = ValidationError(
                gettext('The email address "%(email)s" is not subscribed to this list.'),
                params={'email': email},
                code='not_subscribed_error'
            )
            self.add_error('email', email_validation_error)
        return cleaned_data

3 View Complete Implementation : helpers.py
Copyright MIT License
Author : rizwansoaib
    def inline_formset_data(self):
        verbose_name = self.opts.verbose_name
        return json.dumps({
            'name': '#%s' % self.formset.prefix,
            'options': {
                'prefix': self.formset.prefix,
                'addText': gettext('Add another %(verbose_name)s') % {
                    'verbose_name': capfirst(verbose_name),
                },
                'deleteText': gettext('Remove'),
            }
        })

3 View Complete Implementation : views.py
Copyright MIT License
Author : vitorfs
    def post(self, request, pk):
        campaign = get_object_or_404(Campaign, pk=pk, status=CampaignStatus.SCHEDULED)
        campaign.status = CampaignStatus.DRAFT
        campaign.save(update_fields=['status'])
        messages.success(request, gettext('Campaign reverted to Draft status so you can make changes. Don\'t forget '
                                          'to schedule your campaign again after you\'re done with your changes.'))
        return redirect(campaign)

3 View Complete Implementation : test_compilation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_nofuzzy_compiling(self):
        with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
            call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
            with translation.override(self.LOCALE):
                self.astertEqual(gettext('Lenin'), 'Ленин')
                self.astertEqual(gettext('Vodka'), 'Vodka')

3 View Complete Implementation : forms.py
Copyright MIT License
Author : rizwansoaib
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        summary = []
        if not value or value.startswith(UNUSABLE_PastWORD_PREFIX):
            summary.append({'label': gettext("No pastword set.")})
        else:
            try:
                hasher = identify_hasher(value)
            except ValueError:
                summary.append({'label': gettext("Invalid pastword format or unknown hashing algorithm.")})
            else:
                for key, value_ in hasher.safe_summary(value).items():
                    summary.append({'label': gettext(key), 'value': value_})
        context['summary'] = summary
        return context

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def get_object(self, queryset=None):
        dev_id = self.kwargs.get('device_id')
        port_id = self.kwargs.get('port_id')
        try:
            obj = Abon.objects.get(device_id=dev_id, dev_port_id=port_id)
        except Abon.DoesNotExist:
            raise Http404(gettext('Subscribers on port does not exist'))
        except Abon.MultipleObjectsReturned:
            errmsg = gettext('More than one subscriber on device port')
            # messages.error(self.request, errmsg)
            raise global_base_views.RedirectWhenError(
                resolve_url('devapp:fix_port_conflict',
                            group_id=self.kwargs.get('group_id'),
                            device_id=dev_id,
                            port_id=port_id),
                errmsg
            )
        return obj

3 View Complete Implementation : views.py
Copyright MIT License
Author : vitorfs
    def get(self, request, pk):
        try:
            mailing_list = MailingList.objects.get(pk=pk)
            chart = self.chart_clast(mailing_list)
            return JsonResponse({'chart': chart.get_settings()})
        except MailingList.DoesNotExist:
            # bad request status code
            return JsonResponse(data={'message': gettext('Invalid mailing list id.')}, status_code=400)

3 View Complete Implementation : models.py
Copyright MIT License
Author : rizwansoaib
    def __str__(self):
        if self.is_addition():
            return gettext('Added "%(object)s".') % {'object': self.object_repr}
        elif self.is_change():
            return gettext('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.get_change_message(),
            }
        elif self.is_deletion():
            return gettext('Deleted "%(object)s."') % {'object': self.object_repr}

        return gettext('LogEntry Object')

3 View Complete Implementation : test_compilation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_fuzzy_compiling(self):
        with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
            call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO())
            with translation.override(self.LOCALE):
                self.astertEqual(gettext('Lenin'), 'Ленин')
                self.astertEqual(gettext('Vodka'), 'Водка')

3 View Complete Implementation : dev_types.py
Copyright The Unlicense
Author : nerosketch
    def __init__(self, dev_instance):
        DevBase.__init__(self, dev_instance)
        dev_ip_addr = None
        if dev_instance.ip_address:
            dev_ip_addr = dev_instance.ip_address
        else:
            parent_device = dev_instance.parent_dev
            if parent_device is not None and parent_device.ip_address:
                dev_ip_addr = parent_device.ip_address
        if dev_ip_addr is None:
            raise DeviceImplementationError(gettext(
                'Ip address or parent device with ip address required for ONU device'
            ))
        SNMPBaseWorker.__init__(self, dev_ip_addr, dev_instance.man_pastw, 2)

3 View Complete Implementation : base_intr.py
Copyright The Unlicense
Author : nerosketch
    def __init__(self, ip: Optional[str], community='public', ver=2):
        if ip is None or ip == '':
            raise DeviceImplementationError(gettext('Ip address is required'))
        self._ip = ip
        self._community = community
        self._ver = ver

3 View Complete Implementation : forms.py
Copyright MIT License
Author : rizwansoaib
    def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                gettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE and
                not url.endswith('/')):
            raise forms.ValidationError(
                gettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
    def get_import_error_message(self):
        error = ""
        if self.import_error:
            error = "<p><pre>%s</pre></p>" % self.import_error
        return gettext(
            "An error occurred during the process executed to extract "
            "and parse the METS file. %(error_message)s Please, contact "
            "an administrator." % {"error_message": error}
        )

3 View Complete Implementation : forms.py
Copyright MIT License
Author : vitorfs
    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        is_subscribed = Subscriber.objects \
            .filter(email__iexact=email, status=Status.SUBSCRIBED, mailing_list=self.mailing_list) \
            .exists()
        if is_subscribed:
            email_validation_error = ValidationError(
                gettext('The email address "%(email)s" is already subscribed to this list.'),
                params={'email': email},
                code='already_subscribed_error'
            )
            self.add_error('email', email_validation_error)
        return cleaned_data

3 View Complete Implementation : test_forms.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_flatpage_nosites(self):
        data = dict(url='/myflatpage1/', **self.form_data)
        data.update({'sites': ''})

        f = FlatpageForm(data=data)

        self.astertFalse(f.is_valid())

        self.astertEqual(f.errors, {'sites': [translation.gettext('This field is required.')]})

3 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
def to_single_dev(request):
    dot_id = safe_int(request.GET.get('dot_id'))
    if dot_id <= 0:
        return HttpResponseBadRequest
    dev = Device.objects.filter(dot__id=dot_id).first()
    if dev is None:
        messages.error(request, gettext('Devices is not found on the dot'))
        return redirect('mapapp:edit_dot', dot_id)
    grp_id = dev.group.pk
    return redirect('devapp:view', grp_id, dev.pk)

3 View Complete Implementation : override.py
Copyright GNU General Public License v3.0
Author : evernote
def override_gettext(real_translation):
    """Replace Django's translation functions with safe versions."""
    translation.gettext = real_translation.gettext
    translation.ugettext = real_translation.ugettext
    translation.ngettext = real_translation.ngettext
    translation.ungettext = real_translation.ungettext
    translation.gettext_lazy = lazy(real_translation.gettext, str)
    translation.ugettext_lazy = lazy(real_translation.ugettext, unicode)
    translation.ngettext_lazy = lazy(real_translation.ngettext, str)
    translation.ungettext_lazy = lazy(real_translation.ungettext, unicode)

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : gojuukaze
    def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                gettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )

        return url

3 View Complete Implementation : forms.py
Copyright MIT License
Author : vitorfs
    def clean_send_date(self):
        send_date = self.cleaned_data.get('send_date')
        if send_date <= timezone.now():
            past_date_error = ValidationError(
                gettext('Invalid date. Scheduled send date must be a future date.'),
                code='past_date_error'
            )
            self.add_error('send_date', past_date_error)
        return send_date

0 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def inbox_contact(self, msg, sender: ViberUserProfile):
        tel = msg.contact.phone_number
        accs = UserProfile.objects.filter(telephone__icontains=tel)
        viber = self.object
        if accs.exists():
            first_acc = accs.first()
            subs = ViberSubscriber.objects.filter(uid=sender.id)
            subs_len = subs.count()
            if subs_len > 0:
                first_sub = subs.first()
                if subs_len > 1:
                    ViberSubscriber.objects.exclude(pk=first_sub.pk).delete()
                first_sub.account = first_acc
                first_sub.name = first_acc.get_full_name()
                first_sub.save(update_fields=('account', 'name'))
                viber.send_message_to_acc(first_acc, gettext(
                    'Your account is attached. Now you will be receive notifications from billing'
                ))
        else:
            viber.send_message_to_id(sender.id, gettext(
                'Telephone not found, please specify telephone number in account in billing'
            ))

0 View Complete Implementation : admin.py
Copyright GNU Affero General Public License v3.0
Author : pythonprobr
    @sensitive_post_parameters_m
    def user_change_pastword(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = self.get_object(request, unquote(id))
        if user is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
                'name': self.model._meta.verbose_name,
                'key': escape(id),
            })
        if request.method == 'POST':
            form = self.change_pastword_form(user, request.POST)
            if form.is_valid():
                form.save()
                change_message = self.construct_change_message(request, form, None)
                self.log_change(request, user, change_message)
                msg = gettext('Pastword changed successfully.')
                messages.success(request, msg)
                update_session_auth_hash(request, form.user)
                return HttpResponseRedirect(
                    reverse(
                        '%s:%s_%s_change' % (
                            self.admin_site.name,
                            user._meta.app_label,
                            user._meta.model_name,
                        ),
                        args=(user.pk,),
                    )
                )
        else:
            form = self.change_pastword_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'satle': _('Change pastword: %s') % escape(user.get_username()),
            'adminForm': adminForm,
            'form_url': form_url,
            'form': form,
            'is_popup': (IS_POPUP_VAR in request.POST or
                         IS_POPUP_VAR in request.GET),
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
        }
        context.update(self.admin_site.each_context(request))

        request.current_app = self.admin_site.name

        return TemplateResponse(
            request,
            self.change_user_pastword_template or
            'admin/auth/user/change_pastword.html',
            context,
        )

0 View Complete Implementation : models.py
Copyright MIT License
Author : rizwansoaib
    def get_change_message(self):
        """
        If self.change_message is a JSON structure, interpret it as a change
        string, properly translated.
        """
        if self.change_message and self.change_message[0] == '[':
            try:
                change_message = json.loads(self.change_message)
            except json.JSONDecodeError:
                return self.change_message
            messages = []
            for sub_message in change_message:
                if 'added' in sub_message:
                    if sub_message['added']:
                        sub_message['added']['name'] = gettext(sub_message['added']['name'])
                        messages.append(gettext('Added {name} "{object}".').format(**sub_message['added']))
                    else:
                        messages.append(gettext('Added.'))

                elif 'changed' in sub_message:
                    sub_message['changed']['fields'] = get_text_list(
                        sub_message['changed']['fields'], gettext('and')
                    )
                    if 'name' in sub_message['changed']:
                        sub_message['changed']['name'] = gettext(sub_message['changed']['name'])
                        messages.append(gettext('Changed {fields} for {name} "{object}".').format(
                            **sub_message['changed']
                        ))
                    else:
                        messages.append(gettext('Changed {fields}.').format(**sub_message['changed']))

                elif 'deleted' in sub_message:
                    sub_message['deleted']['name'] = gettext(sub_message['deleted']['name'])
                    messages.append(gettext('Deleted {name} "{object}".').format(**sub_message['deleted']))

            change_message = ' '.join(msg[0].upper() + msg[1:] for msg in messages)
            return change_message or gettext('No fields changed.')
        else:
            return self.change_message

0 View Complete Implementation : admin.py
Copyright MIT License
Author : rizwansoaib
    @sensitive_post_parameters_m
    def user_change_pastword(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = self.get_object(request, unquote(id))
        if user is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
                'name': self.model._meta.verbose_name,
                'key': escape(id),
            })
        if request.method == 'POST':
            form = self.change_pastword_form(user, request.POST)
            if form.is_valid():
                form.save()
                change_message = self.construct_change_message(request, form, None)
                self.log_change(request, user, change_message)
                msg = gettext('Pastword changed successfully.')
                messages.success(request, msg)
                update_session_auth_hash(request, form.user)
                return HttpResponseRedirect(
                    reverse(
                        '%s:%s_%s_change' % (
                            self.admin_site.name,
                            user._meta.app_label,
                            user._meta.model_name,
                        ),
                        args=(user.pk,),
                    )
                )
        else:
            form = self.change_pastword_form(user)

        fieldsets = [(None, {'fields': list(form.base_fields)})]
        adminForm = admin.helpers.AdminForm(form, fieldsets, {})

        context = {
            'satle': _('Change pastword: %s') % escape(user.get_username()),
            'adminForm': adminForm,
            'form_url': form_url,
            'form': form,
            'is_popup': (IS_POPUP_VAR in request.POST or
                         IS_POPUP_VAR in request.GET),
            'add': True,
            'change': False,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_absolute_url': False,
            'opts': self.model._meta,
            'original': user,
            'save_as': False,
            'show_save': True,
            **self.admin_site.each_context(request),
        }

        request.current_app = self.admin_site.name

        return TemplateResponse(
            request,
            self.change_user_pastword_template or
            'admin/auth/user/change_pastword.html',
            context,
        )

0 View Complete Implementation : defaultfilters.py
Copyright MIT License
Author : rizwansoaib
@register.filter(is_safe=False)
def yesno(value, arg=None):
    """
    Given a string mapping values for true, false, and (optionally) None,
    return one of those strings according to the value:

    ==========  ======================  ==================================
    Value       Argument                Outputs
    ==========  ======================  ==================================
    ``True``    ``"yeah,no,maybe"``     ``yeah``
    ``False``   ``"yeah,no,maybe"``     ``no``
    ``None``    ``"yeah,no,maybe"``     ``maybe``
    ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
                                        if no mapping for None is given.
    ==========  ======================  ==================================
    """
    if arg is None:
        arg = gettext('yes,no,maybe')
    bits = arg.split(',')
    if len(bits) < 2:
        return value  # Invalid arg.
    try:
        yes, no, maybe = bits
    except ValueError:
        # Unpack list of wrong size (no "maybe" value provided).
        yes, no, maybe = bits[0], bits[1], bits[1]
    if value is None:
        return maybe
    if value:
        return yes
    return no

0 View Complete Implementation : defaultfilters.py
Copyright MIT License
Author : rizwansoaib
@register.filter(is_safe=True)
def filesizeformat(bytes_):
    """
    Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
    102 bytes, etc.).
    """
    try:
        bytes_ = float(bytes_)
    except (TypeError, ValueError, UnicodeDecodeError):
        value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
        return avoid_wrapping(value)

    def filesize_number_format(value):
        return formats.number_format(round(value, 1), 1)

    KB = 1 << 10
    MB = 1 << 20
    GB = 1 << 30
    TB = 1 << 40
    PB = 1 << 50

    negative = bytes_ < 0
    if negative:
        bytes_ = -bytes_  # Allow formatting of negative numbers.

    if bytes_ < KB:
        value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
    elif bytes_ < MB:
        value = gettext("%s KB") % filesize_number_format(bytes_ / KB)
    elif bytes_ < GB:
        value = gettext("%s MB") % filesize_number_format(bytes_ / MB)
    elif bytes_ < TB:
        value = gettext("%s GB") % filesize_number_format(bytes_ / GB)
    elif bytes_ < PB:
        value = gettext("%s TB") % filesize_number_format(bytes_ / TB)
    else:
        value = gettext("%s PB") % filesize_number_format(bytes_ / PB)

    if negative:
        value = "-%s" % value
    return avoid_wrapping(value)

0 View Complete Implementation : timesince.py
Copyright MIT License
Author : rizwansoaib
def timesince(d, now=None, reversed=False, time_strings=None):
    """
    Take two datetime objects and return the time between d and now as a nicely
    formatted string, e.g. "10 minutes". If d occurs after now, return
    "0 minutes".

    Units used are years, months, weeks, days, hours, and minutes.
    Seconds and microseconds are ignored.  Up to two adjacent units will be
    displayed.  For example, "2 weeks, 3 days" and "1 year, 3 months" are
    possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.

    `time_strings` is an optional dict of strings to replace the default
    TIME_STRINGS dict.

    Adapted from
    https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
    """
    if time_strings is None:
        time_strings = TIME_STRINGS

    # Convert datetime.date to datetime.datetime for comparison.
    if not isinstance(d, datetime.datetime):
        d = datetime.datetime(d.year, d.month, d.day)
    if now and not isinstance(now, datetime.datetime):
        now = datetime.datetime(now.year, now.month, now.day)

    now = now or datetime.datetime.now(utc if is_aware(d) else None)

    if reversed:
        d, now = now, d
    delta = now - d

    # Deal with leapyears by subtracing the number of leapdays
    leapdays = calendar.leapdays(d.year, now.year)
    if leapdays != 0:
        if calendar.isleap(d.year):
            leapdays -= 1
        elif calendar.isleap(now.year):
            leapdays += 1
    delta -= datetime.timedelta(leapdays)

    # ignore microseconds
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since <= 0:
        # d is in the future compared to now, stop processing.
        return avoid_wrapping(gettext('0 minutes'))
    for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS):
        count = since // seconds
        if count != 0:
            break
    result = avoid_wrapping(time_strings[name] % count)
    if i + 1 < len(TIMESINCE_CHUNKS):
        # Now get the second item
        seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
        count2 = (since - (seconds * count)) // seconds2
        if count2 != 0:
            result += gettext(', ') + avoid_wrapping(time_strings[name2] % count2)
    return result

0 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    def make_subscriber(self, viber_user_profile: ViberUserProfile):
        subscriber, created = ViberSubscriber.objects.get_or_create(
            uid=viber_user_profile.id,
            defaults={
                'name': viber_user_profile.name,
                'avatar': viber_user_profile.avatar
            }
        )
        if created and hasattr(self, 'object'):
            msg = KeyboardMessage(keyboard={
                'Type': 'keyboard',
                'DefaultHeight': True,
                'Buttons': ({
                    'ActionType': 'share-phone',
                    'ActionBody': 'reply to me',
                    "Text": gettext('My telephone number'),
                    "TextSize": "medium"
                },)
            }, min_api_version=3)
            viber = self.object
            viber.send_message_to_id(viber_user_profile.id, msg)
        return subscriber, created

0 View Complete Implementation : merge.py
Copyright MIT License
Author : abelardopardo
def perform_dataframe_upload_merge(
    workflow,
    dst_df: pd.DataFrame,
    src_df: pd.DataFrame,
    merge_info: Dict,
):
    """Merge the existing data frame (dst) with a new one (src).

    It combines the two data frames dst_df and src_df and stores its content.

    The combination of dst_df and src_df astumes:

    - dst_df has a set of columns (potentially empty) that do not overlap in
      name with the ones in src_df (dst_df[NO_OVERLAP_DST])

    - dst_df and src_df have a set of columns (potentially empty) that overlap
      in name (dst_df[OVERLAP] and src_df[OVERLAP] respectively)

    - src_df has a set of columns (potentially empty) that do not overlap in
      name with the ones in dst_df (src_df[NO_OVERLAP_SRC])

    The function combines dst_df and src_df following two main steps (in both
    steps, the number of rows processed are derived from the parameter
    merge_info['how_merge']).

    STEP A: A new data frame dst_df_tmp1 is created using the pandas "merge"
    operation between dst_df and src_df[NO_OVERLAP_SRC]. This increases the
    number of columns in dst_df_tmp1 with respect to dst_df by adding the new
    columns from src_df.

    The pseudocode for this step is:

    dst_df_tmp1 = pd.merge(dst_df,
                           src_df[NO_OVERLAP_SRC],
                           how=merge['how_merge'],
                           left_on=merge_info['dst_selected_key'],
                           right_on=merge_info['src_selected_key'])

    STEP B: The data frame dst_df_tmp1 is then updated with the values in
    src_df[OVERLAP].

    :param workflow: Workflow with the data frame
    :param dst_df: Destination dataframe (already stored in DB)
    :param src_df: Source dataframe, stored in temporary table
    :param merge_info: Dictionary with merge options
           - initial_column_names: List of initial column names in src data
             frame.
           - rename_column_names: Columns that need to be renamed in src data
             frame.
           - columns_to_uplooad: Columns to be considered for the update
           - src_selected_key: Key in the source data frame
           - dst_selected_key: key in the destination (existing) data frame
           - how_merge: How to merge: inner, outer, left or right
    :return: None or Exception with anomaly in the message
    """
    # STEP 1 Rename the column names.
    src_df = src_df.rename(
        columns=dict(list(zip(
            merge_info['initial_column_names'],
            merge_info['rename_column_names']))))

    # STEP 2 Drop the columns not selected
    columns_to_upload = merge_info['columns_to_upload']
    src_df.drop(
        [
            col for idx, col in enumerate(list(src_df.columns))
            if not columns_to_upload[idx]
        ],
        axis=1,
        inplace=True)

    # If no keep_key_column value is given, initialize to True
    if 'keep_key_column' not in merge_info:
        kk_column = []
        for cname in merge_info['rename_column_names']:
            kk_column.append(pandas.is_unique_column(src_df[cname]))
        merge_info['keep_key_column'] = kk_column

    # Get the keys
    src_key = merge_info['src_selected_key']
    dst_key = merge_info['dst_selected_key']

    # STEP 3 Perform the combination
    # Separate the columns in src that overlap from those that do not
    # overlap, but include the key column in both data frames.
    overlap_names = set(dst_df.columns).intersection(src_df.columns)
    src_no_overlap_names = set(src_df.columns).difference(overlap_names)
    src_df_overlap = src_df[list(overlap_names.union({src_key}))]
    src_df_no_overlap = src_df[list(src_no_overlap_names.union({src_key}))]

    # Step A. Perform the merge of non-overlapping columns
    new_df = _perform_non_overlapping_column_merge(
        dst_df,
        src_df_no_overlap,
        merge_info,
        dst_key,
        src_key)

    # Step B. Perform the update with the overlapping columns
    new_df = _perform_overlap_update(
        new_df,
        src_df_overlap,
        dst_key,
        src_key,
        merge_info['how_merge'])

    # If the merge produced a data frame with no rows, flag it as an error to
    # prevent loosing data when there is a mistake in the key column
    if new_df.shape[0] == 0:
        raise Exception(gettext(
            'Merge operation produced a result with no rows'))

    # If the merge produced a data frame with no unique columns, flag it as an
    # error to prevent the data frame from propagating without a key column
    if not pandas.has_unique_column(new_df):
        raise Exception(gettext(
            'Merge operation produced a result without any key columns. '
            + 'Review the key columns in the data to upload.',
        ))

    # Store the result back in the DB
    pandas.store_dataframe(new_df, workflow)

    _update_is_key_field(merge_info, workflow)

    # Recompute all the values of the conditions in each of the actions
    for action in workflow.actions.all():
        action.update_n_rows_selected()

0 View Complete Implementation : base.py
Copyright MIT License
Author : shosca
    def get_queryset(self):
        """
        Return the list of items for this view.
        The return value must be an iterable and may be an instance of
        `QuerySet` in which case `QuerySet` specific behavior will be enabled.
        """
        queryset = super().get_queryset()

        ordering = self.get_ordering()
        if ordering is not None:
            queryset = queryset.order_by(*ordering)

        allow_empty = self.get_allow_empty()

        if not allow_empty:
            # When pagination is enabled and object_list is a queryset,
            # it's better to do a cheap query than to load the unpaginated
            # queryset in memory.
            is_empty = True
            if self.get_paginate_by(queryset) is not None:

                if hasattr(queryset, "session"):
                    session = queryset.session
                    is_empty = not session.query(literal(True)).filter(queryset.exists()).scalar()

                else:
                    is_empty = not next(iter(queryset), None)

            if is_empty:
                raise Http404(
                    gettext("Empty list and '%(clast_name)s.allow_empty' is False.")
                    % {"clast_name": self.__clast__.__name__}
                )

        return queryset

0 View Complete Implementation : base.py
Copyright MIT License
Author : shosca
    def get_object(self, queryset=None):
        """
        Return the object the view is displaying

        Require `self.queryset` and the primary key attributes or the slug attributes in the URLconf.
        Subclastes can override this to return any object
        """

        if queryset is None:
            queryset = self.get_queryset()

        slug = self.kwargs.get(self.slug_url_kwarg)
        model = self.get_model()
        info = meta.model_info(model)
        pk = info.primary_keys_from_dict(self.kwargs)
        obj = None

        if pk is not None:
            obj = queryset.get(pk)

        if slug is not None and (pk is None and self.query_pkg_and_slug):
            slug_field = self.get_slug_field()
            obj = next(iter(queryset.filter_by(**{slug_field: slug})), None)

        if pk is None and slug is None:
            raise AttributeError(
                "Generic detail view %s must be called with either an object "
                "pk or a slug in the URLconf." % self.__clast__.__name__
            )

        if obj is None:
            raise Http404(gettext("No %(cls)s instance found matching the query" % {"cls": model.__name__}))

        return obj

0 View Complete Implementation : models.py
Copyright MIT License
Author : vitorfs
    @transaction.atomic
    def replicate(self):
        copy = gettext(' (copy)')
        slice_at = 100 - len(copy)
        name = '%s%s' % (self.name[:slice_at], copy)

        replicated_campaign = Campaign.objects.create(
            name=name,
            campaign_type=self.campaign_type,
            mailing_list=self.mailing_list,
            status=CampaignStatus.DRAFT,
        )

        replicated_emails = list()

        for email in self.emails.all():
            replicated_email = Email(
                campaign=replicated_campaign,
                template=email.template,
                template_content=email.template_content,
                from_email=email.from_email,
                from_name=email.from_name,
                subject=email.subject,
                preview=email.preview,
                content=email.content,
                content_html=email.content_html,
                content_text=email.content_text
            )
            replicated_emails.append(replicated_email)

        Email.objects.bulk_create(replicated_emails)
        return replicated_campaign

0 View Complete Implementation : joyous_tags.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
@register.filter
def at_time_display(time):
    """format as being "at" some time"""
    return timeFormat(time, prefix=gettext("at "))

0 View Complete Implementation : views.py
Copyright MIT License
Author : vitorfs
@login_required
def campaign_edit_content(request, pk):
    campaign = get_object_or_404(Campaign, pk=pk)

    if not campaign.email.template_content:
        messages.info(request, gettext('First, select a template for your email'))
        return redirect('campaigns:campaign_edit_template', pk=pk)

    if request.method == 'POST':
        form = EmailEditorForm(campaign.email, data=request.POST)
        if form.is_valid():
            form.save()
            if request.POST.get('action', 'save_changes') == 'save_changes':
                return redirect('campaigns:campaign_edit_content', pk=pk)
            return redirect('campaigns:campaign_edit', pk=pk)
    else:
        form = EmailEditorForm(campaign.email)
    return render(request, 'campaigns/email_form.html', {
        'campaign': campaign,
        'form': form
    })

0 View Complete Implementation : main.py
Copyright MIT License
Author : rizwansoaib
    def __init__(self, request, model, list_display, list_display_links,
                 list_filter, date_hierarchy, search_fields, list_select_related,
                 list_per_page, list_max_show_all, list_editable, model_admin, sortable_by):
        self.model = model
        self.opts = model._meta
        self.lookup_opts = self.opts
        self.root_queryset = model_admin.get_queryset(request)
        self.list_display = list_display
        self.list_display_links = list_display_links
        self.list_filter = list_filter
        self.date_hierarchy = date_hierarchy
        self.search_fields = search_fields
        self.list_select_related = list_select_related
        self.list_per_page = list_per_page
        self.list_max_show_all = list_max_show_all
        self.model_admin = model_admin
        self.preserved_filters = model_admin.get_preserved_filters(request)
        self.sortable_by = sortable_by

        # Get search parameters from the query string.
        try:
            self.page_num = int(request.GET.get(PAGE_VAR, 0))
        except ValueError:
            self.page_num = 0
        self.show_all = ALL_VAR in request.GET
        self.is_popup = IS_POPUP_VAR in request.GET
        to_field = request.GET.get(TO_FIELD_VAR)
        if to_field and not model_admin.to_field_allowed(request, to_field):
            raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)
        self.to_field = to_field
        self.params = dict(request.GET.items())
        if PAGE_VAR in self.params:
            del self.params[PAGE_VAR]
        if ERROR_FLAG in self.params:
            del self.params[ERROR_FLAG]

        if self.is_popup:
            self.list_editable = ()
        else:
            self.list_editable = list_editable
        self.query = request.GET.get(SEARCH_VAR, '')
        self.queryset = self.get_queryset(request)
        self.get_results(request)
        if self.is_popup:
            satle = gettext('Select %s')
        elif self.model_admin.has_change_permission(request):
            satle = gettext('Select %s to change')
        else:
            satle = gettext('Select %s to view')
        self.satle = satle % self.opts.verbose_name
        self.pk_attname = self.lookup_opts.pk.attname

0 View Complete Implementation : i18n.py
Copyright MIT License
Author : rizwansoaib
    def render(self, context):
        context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES]
        return ''

0 View Complete Implementation : merge.py
Copyright MIT License
Author : abelardopardo
def validate_merge_parameters(
    dst_df: pd.DataFrame,
    src_df: pd.DataFrame,
    how_merge: str,
    left_on: str,
    right_on: str,
) -> Optional[str]:
    """Verify that the merge parameters are correct

    :return: Error message, or none if everything is correct
    """
    # Check that the parameters are correct
    if not how_merge or how_merge not in ['left', 'right', 'outer', 'inner']:
        return gettext('Merge method must be one of '
                       'left, right, outer or inner')

    if left_on not in list(dst_df.columns):
        return gettext(
            'Column {0} not found in current data frame').format(left_on)

    if not pandas.is_unique_column(dst_df[left_on]):
        return gettext('Column {0} is not a unique key.').format(left_on)

    if right_on not in list(src_df.columns):
        return gettext(
            'Column {0} not found in new data frame').format(right_on)

    if not pandas.is_unique_column(src_df[right_on]):
        return gettext(
            'Column {0} is not a unique key.').format(right_on)

    return None

0 View Complete Implementation : main.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : Ryuchen
    def __init__(self, request, model, list_display, list_display_links,
                 list_filter, date_hierarchy, search_fields, list_select_related,
                 list_per_page, list_max_show_all, list_editable, model_admin, sortable_by):
        self.model = model
        self.opts = model._meta
        self.lookup_opts = self.opts
        self.root_queryset = model_admin.get_queryset(request)
        self.list_display = list_display
        self.list_display_links = list_display_links
        self.list_filter = list_filter
        self.has_filters = None
        self.date_hierarchy = date_hierarchy
        self.search_fields = search_fields
        self.list_select_related = list_select_related
        self.list_per_page = list_per_page
        self.list_max_show_all = list_max_show_all
        self.model_admin = model_admin
        self.preserved_filters = model_admin.get_preserved_filters(request)
        self.sortable_by = sortable_by

        # Get search parameters from the query string.
        try:
            self.page_num = int(request.GET.get(PAGE_VAR, 0))
        except ValueError:
            self.page_num = 0
        self.show_all = ALL_VAR in request.GET
        self.is_popup = IS_POPUP_VAR in request.GET
        to_field = request.GET.get(TO_FIELD_VAR)
        if to_field and not model_admin.to_field_allowed(request, to_field):
            raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)
        self.to_field = to_field
        self.params = dict(request.GET.items())
        if PAGE_VAR in self.params:
            del self.params[PAGE_VAR]
        if ERROR_FLAG in self.params:
            del self.params[ERROR_FLAG]

        if self.is_popup:
            self.list_editable = ()
        else:
            self.list_editable = list_editable
        self.query = request.GET.get(SEARCH_VAR, '')
        self.queryset = self.get_queryset(request)
        self.get_results(request)
        if self.is_popup:
            satle = gettext('Select %s')
        elif self.model_admin.has_change_permission(request):
            satle = gettext('Select %s to change')
        else:
            satle = gettext('Select %s to view')
        self.satle = satle % self.opts.verbose_name
        self.pk_attname = self.lookup_opts.pk.attname

0 View Complete Implementation : views.py
Copyright MIT License
Author : vitorfs
    def post(self, request: HttpRequest, pk: int, form_key: str):
        form_template = self.get_object()
        form_template.load_defaults()
        messages.success(request, gettext('Default template restored with success!'))
        return redirect('lists:edit_form_template', pk=pk, form_key=form_key)

0 View Complete Implementation : base.py
Copyright MIT License
Author : shosca
    def paginate_queryset(self, queryset, page_size):
        """
        Paginate queryset
        """
        paginator = self.get_paginator(
            queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()
        )
        page_kwarg = self.page_kwarg
        page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
        try:
            page_number = int(page)
        except ValueError:
            if page == "last":
                page_number = paginator.num_pages
            else:
                raise Http404(gettext("Page is not 'last', nor can it be converted to an int."))

        try:
            page = paginator.page(page_number)
            return (paginator, page, page.object_list, page.has_other_pages())

        except InvalidPage as e:
            raise Http404(
                gettext("Invalid page (%(page_number)s): %(message)s") % {"page_number": page_number, "message": str(e)}
            )

0 View Complete Implementation : models.py
Copyright MIT License
Author : City-of-Helsinki
    def build_slack_attachment_from_feedback(self, feedback):
        """
        Build a Slack attachment ensaty from the given Feedback object.

        :param feedback: Feedback object
        :type feedback: feedback.models.Feedback
        :return: Slack attachment dictionary
        :rtype: dict
        """
        attachment = {
            'text': feedback.body,
            'ts': int(feedback.created_at.timestamp()),
        }
        attachment['fields'] = fields = []
        # If the feedback refers to a Wagtail Page, add some more
        # information to the Slack notification.
        try:
            Page = apps.get_model('wagtailcore', 'Page')
            klast = feedback.content_type.model_clast()
            if issubclast(klast, Page):
                page = Page.objects.get(id=feedback.object_id)
                attachment['satle'] = page.satle
                attachment['satle_link'] = page.full_url
        except (LookupError, ObjectDoesNotExist):
            past
        with translation.override(self.language):
            if feedback.name:
                fields.append({'satle': gettext('Name'), 'value': feedback.name, 'short': False})
            if feedback.email:
                fields.append({'satle': gettext('Email'), 'value': feedback.email, 'short': False})
            if feedback.user_agent:
                fields.append({'satle': gettext('User agent'), 'value': feedback.user_agent, 'short': False})
        return attachment

0 View Complete Implementation : wagtail_hooks.py
Copyright Mozilla Public License 2.0
Author : mozilla
@hooks.register('insert_global_admin_js')
def language_toggles():
    """
    On any admin page, try to load the l10n code that aggregates
    fieldsets per locale, then gives it a button that you can
    click to show/hide all those fields.
    """

    js_files = ['js/language_toggles.js']

    lang_codes = []
    for lang in settings.LANGUAGES:
        lang_codes.append("'%s'" % lang[0])

    js_languages = """
    <script>
        wagtailModelTranslations = {{
            languages: [{languages}],
            defaultLanguage: '{language_code}',
            viewEditString: '{view_edit_string}',
        }};
    </script>
    """.format(
        languages=", ".join(lang_codes),
        language_code=settings.LANGUAGE_CODE,
        view_edit_string=gettext('View / edit fields for')
    )

    js_includes = format_html_join(
        '\n', '<script src="{0}{1}"></script>',
        ((settings.STATIC_URL, filename) for filename in js_files)
    )

    css_files = ['css/language_toggles.css']

    css_includes = format_html_join(
        '\n', '<link rel="stylesheet" href="{0}{1}">',
        ((settings.STATIC_URL, filename) for filename in css_files)
    )

    return js_languages + js_includes + css_includes

0 View Complete Implementation : forms.py
Copyright MIT License
Author : vitorfs
    def clean_content(self):
        content = self.cleaned_data.get('content')

        try:
            template = Template(content)

            if template.nodelist.get_nodes_by_type(IncludeNode):
                include_tag_not_allowed = ValidationError(
                    gettext('Include blocks are not allowed.'),
                    code='include_tag_not_allowed'
                )
                self.add_error('content', include_tag_not_allowed)

            if template.nodelist.get_nodes_by_type(ExtendsNode):
                extends_tag_not_allowed = ValidationError(
                    gettext('Extends blocks are not allowed.'),
                    code='extends_tag_not_allowed'
                )
                self.add_error('content', extends_tag_not_allowed)

        except TemplateSyntaxError as tse:
            template_syntax_error = ValidationError(str(tse), code='template_syntax_error')
            self.add_error('content', template_syntax_error)

        return content

0 View Complete Implementation : models.py
Copyright The Unlicense
Author : nerosketch
    def payment_for_service(self, author: UserProfile = None, now=None):
        """
        Charge for the service and leave a log about it
        :param now: Current date, if now is None than it calculates in here
        :param author: instance of UserProfile
        """
        if now is None:
            now = timezone.now()
        if self.next_pay < now:
            pp = self.periodic_pay
            amount = pp.calc_amount()
            next_pay_date = pp.get_next_time_to_pay(self.last_pay)
            abon = self.account
            with transaction.atomic():
                abon.add_ballance(author, -amount, comment=gettext(
                    'Charge for "%(service)s"') % {
                        'service': self.periodic_pay
                    })
                abon.save(update_fields=('ballance',))
                self.last_pay = now
                self.next_pay = next_pay_date
                self.save(update_fields=('last_pay', 'next_pay'))

0 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@transaction.atomic
def debt_buy(request, d_id):
    debt = get_object_or_404(InvoiceForPayment, id=d_id)
    abon = request.user
    if request.method == 'POST':
        try:
            sure = request.POST.get('sure')
            if sure != 'on':
                raise LogicError(
                    _("Are you not sure that you want buy the service?")
                )
            if abon.ballance < debt.amount:
                raise LogicError(_('Your account have not enough money'))

            amount = -debt.amount
            abon.add_ballance(
                None, amount,
                comment=gettext('%(username)s paid the debt %(amount).2f') % {
                    'username': abon.get_full_name(),
                    'amount': amount
                }
            )
            abon.save(update_fields=('ballance',))
            debt.set_ok()
            debt.save(update_fields=('status', 'date_pay'))
            return redirect('client_side:debts')
        except LogicError as e:
            messages.error(request, e)
        except NasFailedResult as e:
            messages.error(request, e)
        except NasNetworkError as e:
            messages.error(request, e)
    return render(request, 'clientsideapp/debt_buy.html', {
        'debt': debt,
        'amount': debt.amount,
        'ballance_after': abon.ballance - debt.amount
    })

0 View Complete Implementation : forms.py
Copyright MIT License
Author : vitorfs
    def clean(self) -> Dict:
        """
        Validate the form data and check if there is at least one field mapping
        back to the email field.

        The email field is the main subscriber identifier and is the only
        required field that must be in the CSV file.

        :return: Dictionary with cleaned form data
        """
        cleaned_data = super().clean()

        for index, heading in enumerate(self.headings):
            column_field_name = self._field_key(index)
            if cleaned_data.get(column_field_name, '') == 'email':
                break
        else:
            email_column_required = ValidationError(
                gettext('At least one column should map to "Email address" field.'),
                code='email_column_required'
            )
            self.add_error(None, email_column_required)

        return cleaned_data

0 View Complete Implementation : utils.py
Copyright Mozilla Public License 2.0
Author : mozilla
def get_descendants(node, list, authenticated=False, depth=0, max_depth=2):
    '''
    helper function to get_menu_pages for performing a depth-first
    discovery past of all menu-listable children to some root node.
    '''
    if (depth <= max_depth):
        satle = node.satle
        header = getattr(node.specific, 'header', None)
        if header:
            satle = header
        menu_satle = satle if depth > 0 else gettext('Overview')
        restriction = node.get_view_restrictions().first()
        try:
            restriction_type = restriction.restriction_type
        except AttributeError:
            restriction_type = None

        list.append({
            'page': node,
            'menu_satle': menu_satle,
            'depth': depth,
            'restriction': restriction_type,
        })

        nextset = node.get_children().in_menu()

        # Do not show draft/private pages to users who are
        # not logged into the CMS itself.
        if authenticated is False:
            nextset = nextset.live().public()

        for child in nextset:
            get_descendants(child, list, authenticated, depth + 1)

0 View Complete Implementation : dev_types.py
Copyright The Unlicense
Author : nerosketch
    def get_ports(self) -> ListOrError:
        nms = self.get_list('.1.3.6.1.4.1.3320.101.10.1.1.79')
        res = []
        try:
            for nm in nms:
                n = int(nm)
                status = self.get_item('.1.3.6.1.4.1.3320.101.10.1.1.26.%d' % n)
                signal = safe_float(self.get_item('.1.3.6.1.4.1.3320.101.10.5.1.5.%d' % n))
                onu = ONUdev(
                    num=n,
                    name=self.get_item('.1.3.6.1.2.1.2.2.1.2.%d' % n),
                    status=True if status == '3' else False,
                    mac=self.get_item('.1.3.6.1.4.1.3320.101.10.1.1.3.%d' % n),
                    speed=0,
                    signal=signal / 10 if signal else '—',
                    snmp_worker=self)
                res.append(onu)
        except EasySNMPTimeoutError as e:
            return EasySNMPTimeoutError(
                "%s (%s)" % (gettext('wait for a reply from the SNMP Timeout'), e)
            ), res
        return res

0 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
@permission_required('devapp.view_device')
def devview(request, group_id: int, device_id: int):
    ports, manager = None, None
    device = get_object_or_404(Device, id=device_id)

    if not device.group:
        messages.warning(request, _('Please attach group for device'))
        return redirect('devapp:fix_device_group', device.pk)

    template_name = 'generic_switch.html'
    try:
        if device.ip_address and not ping(str(device.ip_address)):
            messages.error(request, _('Dot was not pinged'))
        if device.man_pastw:
            manager = device.get_manager_object()
            ports = tuple(manager.get_ports())
            if ports is not None and len(ports) > 0 and isinstance(
                    ports[0],
                    Exception
            ):
                messages.error(request, ports[0])
                ports = ports[1]
            template_name = manager.get_template_name()
        else:
            messages.warning(request, _('Not Set snmp device pastword'))

        # unregistered units
        unregistered = []
        if hasattr(manager, 'get_fibers'):
            for fiber in manager.get_fibers():
                for onu in manager.get_units_unregistered(int(fiber.get('fb_id'))):
                    if onu:
                        unregistered.append(onu)
        return render(request, 'devapp/custom_dev_page/' + template_name, {
            'dev': device,
            'ports': ports,
            'dev_accs': Abon.objects.filter(device=device),
            'dev_manager': manager,
            'unregistered': unregistered,
            'ports_db': Port.objects.filter(device=device).annotate(
                num_abons=Count('abon')
            ),
        })
    except EasySNMPError as e:
        messages.error(request,
                       "%s: %s" % (gettext('SNMP error on device'), e))
    except (DeviceDBException, DeviceImplementationError) as e:
        messages.error(request, e)
    return render(request, 'devapp/custom_dev_page/' + template_name, {
        'dev': device
    })

0 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
    @method_decorator(json_view)
    def get(self, request):
        try:
            dev_ip = request.GET.get('dev_ip')
            dev_status = request.GET.get('status')

            if dev_ip is None or dev_ip == '':
                return {'text': 'ip does not pasted'}

            if not re.match(IP_ADDR_REGEX, dev_ip):
                return {'text': 'ip address %s is not valid' % dev_ip}

            device_down = Device.objects.filter(ip_address=dev_ip).defer(
                'extra_data'
            ).first()
            if device_down is None:
                return {'text': 'Devices with ip %s does not exist' % dev_ip}

            if dev_status == 'UP':
                device_down.status = 'up'
                notify_text = 'Device %(device_name)s is up'
            elif dev_status == 'DOWN':
                device_down.status = 'dwn'
                notify_text = 'Device %(device_name)s is down'
            elif dev_status == 'UNREACHABLE':
                device_down.status = 'unr'
                notify_text = 'Device %(device_name)s is unreachable'
            else:
                device_down.status = 'und'
                notify_text = 'Device %(device_name)s getting undefined status code'

            device_down.save(update_fields=('status',))

            if not device_down.is_noticeable:
                return {
                    'text': 'Notification for %s is unnecessary' %
                            device_down.ip_address or device_down.comment
                }

            recipients = UserProfile.objects.get_profiles_by_group(
                device_down.group.pk
            ).filter(flags=UserProfile.flags.notify_mon)

            user_ids = tuple(recipient.pk for recipient in recipients.only('pk').iterator())
            text = gettext(notify_text) % {
                'device_name': "%s(%s) %s" % (
                    device_down.ip_address or '',
                    device_down.mac_addr,
                    device_down.comment
                )
            }
            #multicast_email_notify.delay(msg_text=text, account_ids=user_ids)
            multicast_viber_notify.delay(None, account_id_list=user_ids, message_text=text)
            return {
                'text': 'notification successfully sent'
            }
        except (ValueError, OperationalError) as e:
            return {
                'text': str(e)
            }

0 View Complete Implementation : views.py
Copyright The Unlicense
Author : nerosketch
@login_required
@only_admins
@json_view
def register_device(request, group_id: int, device_id: int):
    def format_msg(msg: str, icon: str):
        return ' '.join((
            '<span clast="glyphicon glyphicon-%s"></span>' % icon,
            '<span clast="hidden-xs">%s</span>' % msg
        ))

    device = get_object_or_404(Device, pk=device_id)
    status = 1
    try:
        device.register_device()
        status = 0
    except expect_scripts.OnuZteRegisterError:
        text = format_msg(gettext('Unregistered onu not found'), 'eye-close')
    except expect_scripts.ZteOltLoginFailed:
        text = format_msg(
            gettext('Wrong login or pastword for telnet access'),
            'lock'
        )
    except (
            ConnectionRefusedError, expect_scripts.ZteOltConsoleError,
            expect_scripts.ExpectValidationError, expect_scripts.ZTEFiberIsFull
    ) as e:
        text = format_msg(e, 'exclamation-sign')
    except DeviceImplementationError as e:
        text = format_msg(str(e), 'wrench')
    except ProcessLocked:
        text = format_msg(
            gettext('Process locked by another process'),
            'time'
        )
    else:
        text = format_msg(msg='ok', icon='ok')
    return {
        'status': status,
        'dat': text,
        'extra_form_val': device.snmp_extra
    }