当前位置: 首页>>代码示例>>Python>>正文


Python ErrorList.append方法代码示例

本文整理汇总了Python中django.forms.utils.ErrorList.append方法的典型用法代码示例。如果您正苦于以下问题:Python ErrorList.append方法的具体用法?Python ErrorList.append怎么用?Python ErrorList.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.forms.utils.ErrorList的用法示例。


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

示例1: clean_deck_order

# 需要导入模块: from django.forms.utils import ErrorList [as 别名]
# 或者: from django.forms.utils.ErrorList import append [as 别名]
    def clean_deck_order(self):
        """
        Cleans and validates the JSON POSTed in the deck_order field.
        This field describes how decks should be sorted in the collection.
        Errors are manually added to the errorlist because this is a custom field.
        """
        field = 'deck_order'
        deck_data = []
        errstr = ''
        errors = ErrorList()

        if field in self.data:
            deck_order = json.loads(self.data[field])
            if 'data' in deck_order:
                deck_data = deck_order['data']

        for d in deck_data:
            if ('deck_id' in d and 'sort_order' in d):
                try:
                    int(d['sort_order'])
                except ValueError:
                    errstr = "deck %s has invalid sort value: %s" % (d['deck_id'], d['sort_order'])
                    errors.append(errstr)
            else:
                errstr = "deck_id and sort_order required"
                errors.append(errstr)
                break

        if errors:
            self._errors.setdefault(field, errors)
            raise forms.ValidationError("Deck order field has errors")

        self.cleaned_data['deck_order'] = deck_data
开发者ID:Harvard-ATG,项目名称:HarvardCards,代码行数:35,代码来源:forms.py

示例2: account_login

# 需要导入模块: from django.forms.utils import ErrorList [as 别名]
# 或者: from django.forms.utils.ErrorList import append [as 别名]
def account_login(request):
    if request.user.is_authenticated():
        return redirect('home')
    else:
        if request.POST:
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                users = UserAccount.objects.filter(email=login_form.cleaned_data['email'].lower())
                if len(users) > 0:
                    user = authenticate(email=users[0].email, password=login_form.cleaned_data['password'])
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            return HttpResponseRedirect(request.POST['next'])
                    else:
                        # user does not authenticate
                        errors = ErrorList()
                        errors = login_form._errors.setdefault(forms.NON_FIELD_ERRORS, errors)
                        errors.append('The password for this account is incorrect.')
                else:
                    # user doesn't exist
                    errors = ErrorList()
                    errors = login_form._errors.setdefault(forms.NON_FIELD_ERRORS, errors)
                    errors.append('There is no account registered with this e-mail address.')
        else:
            login_form = LoginForm()
        return render(request, 'general/login.html', {'form': login_form, 'next': request.GET['next'] if request.GET and 'next' in request.GET.keys() else None})
开发者ID:psyonara,项目名称:agonizomai,代码行数:29,代码来源:views.py

示例3: login_view

# 需要导入模块: from django.forms.utils import ErrorList [as 别名]
# 或者: from django.forms.utils.ErrorList import append [as 别名]
def login_view(request):
    """
    Standard Django login, with additions:
        Lowercase the login email (username)
        Check user has accepted ToS, if any.
    """
    if request.method == "POST":
        redirect_to = request.POST.get('next', request.GET.get('next', False))
        if not redirect_to:
            redirect_to = reverse('seed:home')

        form = LoginForm(request.POST)
        if form.is_valid():
            new_user = authenticate(
                username=form.cleaned_data['email'].lower(),
                password=form.cleaned_data['password']
            )
            if new_user and new_user.is_active:
                # determine if user has accepted ToS, if one exists
                try:
                    user_accepted_tos = has_user_agreed_latest_tos(new_user)
                except NoActiveTermsOfService:
                    # there's no active ToS, skip interstitial
                    user_accepted_tos = True

                if user_accepted_tos:
                    login(request, new_user)
                    return HttpResponseRedirect(redirect_to)
                else:
                    # store login info for django-tos to handle
                    request.session['tos_user'] = new_user.pk
                    request.session['tos_backend'] = new_user.backend
                    context = RequestContext(request)
                    context.update({
                        'next': redirect_to,
                        'tos': TermsOfService.objects.get_current_tos()
                    })
                    return render_to_response(
                        'tos/tos_check.html',
                        context_instance=context
                    )
            else:
                errors = ErrorList()
                errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)
                errors.append('Username and/or password were invalid.')
    else:
        form = LoginForm()
    return render_to_response(
        'landing/login.html',
        locals(),
        context_instance=RequestContext(request),
    )
开发者ID:mmclark,项目名称:seed,代码行数:54,代码来源:views.py

示例4: clean

# 需要导入模块: from django.forms.utils import ErrorList [as 别名]
# 或者: from django.forms.utils.ErrorList import append [as 别名]
    def clean(self, value):
        """
        Validates every value in the given list. A value is validated against
        the corresponding Field in self.fields.

        For example, if this MultiValueField was instantiated with
        fields=(DateField(), TimeField()), clean() would call
        DateField.clean(value[0]) and TimeField.clean(value[1]).
        """
        clean_data = []
        errors = ErrorList()
        if not value or isinstance(value, (list, tuple)):
            if not value or not [v for v in value if v not in self.empty_values]:
                if self.required:
                    raise ValidationError(self.error_messages['required'], code='required')
                else:
                    return self.compress([])
        else:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        for i, field in enumerate(self.fields):
            try:
                field_value = value[i]
            except IndexError:
                field_value = None
            if field_value in self.empty_values:
                if self.require_all_fields:
                    # Raise a 'required' error if the MultiValueField is
                    # required and any field is empty.
                    if self.required:
                        raise ValidationError(self.error_messages['required'], code='required')
                elif field.required:
                    # Otherwise, add an 'incomplete' error to the list of
                    # collected errors and skip field cleaning, if a required
                    # field is empty.
                    if field.error_messages['incomplete'] not in errors:
                        errors.append(field.error_messages['incomplete'])
                    continue
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter. Skip duplicates.
                errors.extend(m for m in e.error_list if m not in errors)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        self.run_validators(out)
        return out
开发者ID:AvaniLodaya,项目名称:django,代码行数:53,代码来源:fields.py

示例5: clean

# 需要导入模块: from django.forms.utils import ErrorList [as 别名]
# 或者: from django.forms.utils.ErrorList import append [as 别名]
    def clean(self, value):
        cleaned_data = []
        errors = {}
        non_block_errors = ErrorList()
        for i, child in enumerate(value):  # child is a StreamChild instance
            try:
                cleaned_data.append(
                    (child.block.name, child.block.clean(child.value), child.id)
                )
            except ValidationError as e:
                errors[i] = ErrorList([e])

        if self.meta.min_num is not None and self.meta.min_num > len(value):
            non_block_errors.append(ValidationError(
                _('The minimum number of items is %d') % self.meta.min_num
            ))
        elif self.required and len(value) == 0:
            non_block_errors.append(ValidationError(_('This field is required.')))

        if self.meta.max_num is not None and self.meta.max_num < len(value):
            non_block_errors.append(ValidationError(
                _('The maximum number of items is %d') % self.meta.max_num
            ))

        if self.meta.block_counts:
            block_counts = collections.defaultdict(int)
            for item in value:
                block_counts[item.block_type] += 1

            for block_name, min_max in self.meta.block_counts.items():
                block = self.child_blocks[block_name]
                max_num = min_max.get('max_num', None)
                min_num = min_max.get('min_num', None)
                block_count = block_counts[block_name]
                if min_num is not None and min_num > block_count:
                    non_block_errors.append(ValidationError(
                        '{}: {}'.format(block.label, _('The minimum number of items is %d') % min_num)
                    ))
                if max_num is not None and max_num < block_count:
                    non_block_errors.append(ValidationError(
                        '{}: {}'.format(block.label, _('The maximum number of items is %d') % max_num)
                    ))

        if errors or non_block_errors:
            # The message here is arbitrary - outputting error messages is delegated to the child blocks,
            # which only involves the 'params' list
            raise StreamBlockValidationError(block_errors=errors, non_block_errors=non_block_errors)

        return StreamValue(self, cleaned_data)
开发者ID:morris-tech,项目名称:wagtail,代码行数:51,代码来源:stream_block.py


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