• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python messages.error函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中weblate.trans.messages.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: new_language

def new_language(request, project, subproject):
    obj = get_subproject(request, project, subproject)

    if not can_add_translation(request.user, obj.project):
        raise PermissionDenied()

    form = get_new_language_form(request, obj)(obj, request.POST)

    if form.is_valid():
        langs = form.cleaned_data['lang']
        if isinstance(langs, string_types):
            langs = [langs]
        for language in Language.objects.filter(code__in=langs):
            if obj.new_lang == 'contact':
                notify_new_language(obj, language, request.user)
                messages.success(
                    request,
                    _(
                        "A request for a new translation has been "
                        "sent to the project's maintainers."
                    )
                )
            elif obj.new_lang == 'add':
                obj.add_new_language(language, request)
    else:
        messages.error(
            request,
            _('Invalid language chosen!')
        )

    return redirect(obj)
开发者ID:ccfwwm,项目名称:weblate,代码行数:31,代码来源:basic.py


示例2: reset_password

def reset_password(request):
    """
    Password reset handling.
    """
    if "email" not in load_backends(BACKENDS).keys():
        messages.error(request, _("Can not reset password, email authentication is disabled!"))
        return redirect("login")

    if request.method == "POST":
        form = ResetForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data["email"]
            user.set_unusable_password()
            user.save()

            # Force creating new session
            request.session.create()
            if request.user.is_authenticated():
                logout(request)

            request.session["password_reset"] = True
            return complete(request, "email")
    else:
        form = ResetForm()

    return render(request, "accounts/reset.html", {"title": _("Password reset"), "form": form})
开发者ID:dtschan,项目名称:weblate,代码行数:26,代码来源:views.py


示例3: perform_suggestion

def perform_suggestion(unit, form, request):
    '''
    Handle suggesion saving.
    '''
    if form.cleaned_data['target'][0] == '':
        messages.error(request, _('Your suggestion is empty!'))
        # Stay on same entry
        return False
    elif not can_suggest(request.user, unit.translation):
        # Need privilege to add
        messages.error(
            request,
            _('You don\'t have privileges to add suggestions!')
        )
        # Stay on same entry
        return False
    # Invite user to become translator if there is nobody else
    recent_changes = Change.objects.content(True).filter(
        translation=unit.translation,
    ).exclude(
        user=None
    )
    if not recent_changes.exists():
        messages.info(request, _(
            'There is currently no active translator for this '
            'translation, please consider becoming a translator '
            'as your suggestion might otherwise remain unreviewed.'
        ))
    # Create the suggestion
    Suggestion.objects.add(
        unit,
        join_plural(form.cleaned_data['target']),
        request,
    )
    return True
开发者ID:Yixf-Self,项目名称:weblate,代码行数:35,代码来源:edit.py


示例4: auto_translation

def auto_translation(request, project, subproject, lang):
    translation = get_translation(request, project, subproject, lang)
    project = translation.subproject.project
    if not can_automatic_translation(request.user, project):
        raise PermissionDenied()

    autoform = AutoForm(translation, request.user, request.POST)

    if translation.subproject.locked or not autoform.is_valid():
        messages.error(request, _('Failed to process form!'))
        return redirect(translation)

    updated = auto_translate(
        request.user,
        translation,
        autoform.cleaned_data['subproject'],
        autoform.cleaned_data['inconsistent'],
        autoform.cleaned_data['overwrite']
    )

    import_message(
        request, updated,
        _('Automatic translation completed, no strings were updated.'),
        ungettext(
            'Automatic translation completed, %d string was updated.',
            'Automatic translation completed, %d strings were updated.',
            updated
        )
    )

    return redirect(translation)
开发者ID:Yixf-Self,项目名称:weblate,代码行数:31,代码来源:edit.py


示例5: comment

def comment(request, pk):
    '''
    Adds new comment.
    '''
    translation = get_object_or_404(Unit, pk=pk)
    translation.check_acl(request)

    form = CommentForm(request.POST)

    if form.is_valid():
        if form.cleaned_data['scope'] == 'global':
            lang = None
        else:
            lang = translation.translation.language
        Comment.objects.add(
            translation,
            request.user,
            lang,
            form.cleaned_data['comment']
        )
        messages.success(request, _('Posted new comment'))
    else:
        messages.error(request, _('Failed to add comment!'))

    return redirect(request.POST.get('next', translation))
开发者ID:Yixf-Self,项目名称:weblate,代码行数:25,代码来源:edit.py


示例6: save_zen

def save_zen(request, project, subproject, lang):
    '''
    Save handler for zen mode.
    '''
    translation = get_translation(request, project, subproject, lang)
    user_locked = translation.is_user_locked(request.user)

    form = TranslationForm(translation, None, request.POST)
    if not can_translate(request.user, translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
    elif not form.is_valid():
        messages.error(request, _('Failed to save translation!'))
    elif not user_locked:
        unit = form.cleaned_data['unit']

        perform_translation(unit, form, request)

    return render(
        request,
        'zen-response.html',
        {},
    )
开发者ID:Yixf-Self,项目名称:weblate,代码行数:25,代码来源:edit.py


示例7: mail_admins_contact

def mail_admins_contact(request, subject, message, context, sender):
    '''
    Sends a message to the admins, as defined by the ADMINS setting.
    '''
    LOGGER.info(
        'contact form from %s',
        sender,
    )
    if not settings.ADMINS:
        messages.error(
            request,
            _('Message could not be sent to administrator!')
        )
        LOGGER.error(
            'ADMINS not configured, can not send message!'
        )
        return

    mail = EmailMultiAlternatives(
        '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject % context),
        message % context,
        to=[a[1] for a in settings.ADMINS],
        headers={'Reply-To': sender},
    )

    mail.send(fail_silently=False)

    messages.success(
        request,
        _('Message has been sent to administrator.')
    )
开发者ID:Yixf-Self,项目名称:weblate,代码行数:31,代码来源:views.py


示例8: upload_dictionary

def upload_dictionary(request, project, lang):
    prj = get_project(request, project)
    lang = get_object_or_404(Language, code=lang)

    form = DictUploadForm(request.POST, request.FILES)
    if form.is_valid():
        try:
            count = Dictionary.objects.upload(
                request,
                prj,
                lang,
                request.FILES['file'],
                form.cleaned_data['method']
            )
            import_message(
                request, count,
                _('No words to import found in file.'),
                ungettext(
                    'Imported %d word from the uploaded file.',
                    'Imported %d words from the uploaded file.',
                    count
                )
            )
        except Exception as error:
            report_error(error, sys.exc_info(), request)
            messages.error(
                request, _('File upload has failed: %s') % force_text(error)
            )
    else:
        messages.error(request, _('Failed to process form!'))
    return redirect(
        'show_dictionary',
        project=prj.slug,
        lang=lang.code
    )
开发者ID:Yixf-Self,项目名称:weblate,代码行数:35,代码来源:dictionary.py


示例9: check_acl

 def check_acl(self, request):
     """Raises an error if user is not allowed to access this project."""
     if not self.has_acl(request.user):
         messages.error(
             request,
             _('You are not allowed to access project %s.') % self.name
         )
         raise PermissionDenied
开发者ID:Yixf-Self,项目名称:weblate,代码行数:8,代码来源:project.py


示例10: _get_queryset_language

 def _get_queryset_language(self):
     """
     Filtering by language
     """
     if self.translation is None and "lang" in self.request.GET:
         try:
             self.language = Language.objects.get(code=self.request.GET["lang"])
         except Language.DoesNotExist:
             messages.error(self.request, _("Failed to find matching language!"))
开发者ID:nijel,项目名称:weblate,代码行数:9,代码来源:changes.py


示例11: _get_queryset_user

 def _get_queryset_user(self):
     """
     Filtering by user
     """
     if "user" in self.request.GET:
         try:
             self.user = User.objects.get(username=self.request.GET["user"])
         except User.DoesNotExist:
             messages.error(self.request, _("Failed to find matching user!"))
开发者ID:nijel,项目名称:weblate,代码行数:9,代码来源:changes.py


示例12: perform_translation

def perform_translation(unit, form, request):
    '''
    Handles translation and stores it to a backend.
    '''
    # Remember old checks
    oldchecks = set(
        unit.active_checks().values_list('check', flat=True)
    )

    # Run AutoFixes on user input
    if not unit.translation.is_template():
        new_target, fixups = fix_target(form.cleaned_data['target'], unit)
    else:
        new_target = form.cleaned_data['target']
        fixups = []

    # Save
    saved = unit.translate(
        request,
        new_target,
        form.cleaned_data['fuzzy']
    )

    # Warn about applied fixups
    if len(fixups) > 0:
        messages.info(
            request,
            _('Following fixups were applied to translation: %s') %
            ', '.join([force_text(f) for f in fixups])
        )

    # Get new set of checks
    newchecks = set(
        unit.active_checks().values_list('check', flat=True)
    )

    # Did we introduce any new failures?
    if saved and newchecks > oldchecks:
        # Show message to user
        messages.error(
            request,
            _(
                'Some checks have failed on your translation: {0}'
            ).format(
                ', '.join(
                    [force_text(CHECKS[check].name) for check in newchecks]
                )
            )
        )
        # Stay on same entry
        return False

    return True
开发者ID:Yixf-Self,项目名称:weblate,代码行数:53,代码来源:edit.py


示例13: search

def search(request):
    """
    Performs site-wide search on units.
    """
    search_form = SiteSearchForm(request.GET)
    context = {
        'search_form': search_form,
    }

    if search_form.is_valid():
        # Filter results by ACL
        acl_projects = Project.objects.get_acl_ids(request.user)

        units = Unit.objects.search(
            None,
            search_form.cleaned_data,
        ).filter(
            translation__subproject__project_id__in=acl_projects
        ).select_related(
            'translation',
        )

        limit = request.GET.get('limit', 50)
        page = request.GET.get('page', 1)

        paginator = Paginator(units, limit)

        try:
            units = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            units = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of
            # results.
            units = paginator.page(paginator.num_pages)

        context['page_obj'] = units
        context['title'] = _('Search for %s') % (
            search_form.cleaned_data['q']
        )
        context['query_string'] = search_form.urlencode()
        context['search_query'] = search_form.cleaned_data['q']
    else:
        messages.error(request, _('Invalid search query!'))

    return render(
        request,
        'search.html',
        context
    )
开发者ID:ccfwwm,项目名称:weblate,代码行数:51,代码来源:basic.py


示例14: _get_queryset_project

 def _get_queryset_project(self):
     """
     Filtering by translation/project.
     """
     if "project" in self.request.GET:
         try:
             self.project, self.subproject, self.translation = get_project_translation(
                 self.request,
                 self.request.GET.get("project", None),
                 self.request.GET.get("subproject", None),
                 self.request.GET.get("lang", None),
             )
         except Http404:
             messages.error(self.request, _("Failed to find matching project!"))
开发者ID:nijel,项目名称:weblate,代码行数:14,代码来源:changes.py


示例15: check_user_form

def check_user_form(request, project):
    obj = get_project(request, project)

    if not can_manage_acl(request.user, obj):
        raise PermissionDenied()

    form = UserManageForm(request.POST)

    if form.is_valid():
        return obj, form
    else:
        for error in form.errors:
            for message in form.errors[error]:
                messages.error(request, message)
        return obj, None
开发者ID:Yixf-Self,项目名称:weblate,代码行数:15,代码来源:acl.py


示例16: show_form_errors

def show_form_errors(request, form):
    '''
    Shows all form errors as a message.
    '''
    for error in form.non_field_errors():
        messages.error(request, error)
    for field in form:
        for error in field.errors:
            messages.error(
                request,
                _('Error in parameter %(field)s: %(error)s') % {
                    'field': field.name,
                    'error': error
                }
            )
开发者ID:Yixf-Self,项目名称:weblate,代码行数:15,代码来源:edit.py


示例17: execute_locked

def execute_locked(request, obj, message, call, *args, **kwargs):
    """
    Helper function to catch possible lock exception.
    """
    try:
        result = call(request, *args, **kwargs)
        # With False the call is supposed to show errors on its own
        if result is None or result:
            messages.success(request, message)
    except FileLockException:
        messages.error(
            request,
            _('Failed to lock the repository, another operation in progress.')
        )

    return redirect_param(obj, '#repository')
开发者ID:Yixf-Self,项目名称:weblate,代码行数:16,代码来源:git.py


示例18: add_host_key

def add_host_key(request):
    """
    Adds host key for a host.
    """
    host = request.POST.get('host', '')
    port = request.POST.get('port', '')
    if len(host) == 0:
        messages.error(request, _('Invalid host name given!'))
    else:
        cmdline = ['ssh-keyscan']
        if port:
            cmdline.extend(['-p', port])
        cmdline.append(host)
        try:
            output = subprocess.check_output(
                cmdline,
                stderr=subprocess.STDOUT,
                env=get_clean_env(),
            )
            keys = []
            for key in output.decode('utf-8').splitlines():
                key = key.strip()
                if not is_key_line(key):
                    continue
                keys.append(key)
                host, keytype, fingerprint = parse_hosts_line(key)
                messages.warning(
                    request,
                    _(
                        'Added host key for %(host)s with fingerprint '
                        '%(fingerprint)s (%(keytype)s), '
                        'please verify that it is correct.'
                    ) % {
                        'host': host,
                        'fingerprint': fingerprint,
                        'keytype': keytype,
                    }
                )
            if len(keys) == 0:
                messages.error(
                    request,
                    _('Failed to fetch public key for a host!')
                )
            with open(ssh_file(KNOWN_HOSTS), 'a') as handle:
                for key in keys:
                    handle.write('%s\n' % key)
        except subprocess.CalledProcessError as exc:
            messages.error(
                request,
                _('Failed to get host key: %s') % exc.output
            )
        except OSError as exc:
            messages.error(
                request,
                _('Failed to get host key: %s') % str(exc)
            )
开发者ID:Yixf-Self,项目名称:weblate,代码行数:56,代码来源:ssh.py


示例19: handle_translate

def handle_translate(translation, request, user_locked,
                     this_unit_url, next_unit_url):
    '''
    Saves translation or suggestion to database and backend.
    '''
    # Antispam protection
    antispam = AntispamForm(request.POST)
    if not antispam.is_valid():
        # Silently redirect to next entry
        return HttpResponseRedirect(next_unit_url)

    # Check whether translation is not outdated
    translation.check_sync()

    form = TranslationForm(translation, None, request.POST)
    if not form.is_valid():
        return

    unit = form.cleaned_data['unit']
    go_next = True

    if 'suggest' in request.POST:
        go_next = perform_suggestion(unit, form, request)
    elif not can_translate(request.user, unit.translation):
        messages.error(
            request,
            _('You don\'t have privileges to save translations!')
        )
    elif not user_locked:
        # Custom commit message
        message = request.POST.get('commit_message')
        if message and message != unit.translation.commit_message:
            # Commit pending changes so that they don't get new message
            unit.translation.commit_pending(request, request.user)
            # Store new commit message
            unit.translation.commit_message = message
            unit.translation.save()

        go_next = perform_translation(unit, form, request)

    # Redirect to next entry
    if go_next:
        return HttpResponseRedirect(next_unit_url)
    else:
        return HttpResponseRedirect(this_unit_url)
开发者ID:Yixf-Self,项目名称:weblate,代码行数:45,代码来源:edit.py


示例20: _get_queryset_project

 def _get_queryset_project(self):
     """
     Filtering by translation/project.
     """
     if 'project' in self.request.GET:
         try:
             self.project, self.subproject, self.translation = \
                 get_project_translation(
                     self.request,
                     self.request.GET.get('project', None),
                     self.request.GET.get('subproject', None),
                     self.request.GET.get('lang', None),
                 )
         except Http404:
             messages.error(
                 self.request,
                 _('Failed to find matching project!')
             )
开发者ID:dtschan,项目名称:weblate,代码行数:18,代码来源:changes.py



注:本文中的weblate.trans.messages.error函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python search.fulltext_search函数代码示例发布时间:2022-05-26
下一篇:
Python forms.WordForm类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap