當前位置: 首頁>>代碼示例>>Python>>正文


Python utils.ErrorList方法代碼示例

本文整理匯總了Python中django.forms.utils.ErrorList方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.ErrorList方法的具體用法?Python utils.ErrorList怎麽用?Python utils.ErrorList使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.forms.utils的用法示例。


在下文中一共展示了utils.ErrorList方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None,
                 offering=None, userid=None, enforced_prep_min=0):
        super(TUGForm, self).__init__(data, files, auto_id, prefix, initial,
                 error_class, label_suffix, empty_permitted, instance)
        # see old revisions (git id 1d1d2f9) for a dropdown
        if userid is not None and offering is not None:
            member = Member.objects.exclude(role='DROP').get(person__userid=userid, offering=offering)
        elif instance is not None:
            member = instance.member
        else:
            assert False

        self.enforced_prep_min = enforced_prep_min

        self.initial['member'] = member
        self.fields['member'].widget = forms.widgets.HiddenInput()
        
        self.subforms = self.__construct_subforms(data, initial, instance) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:22,代碼來源:forms.py

示例2: __init__

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False):
        self.is_bound = data is not None or files is not None
        self.data = data or {}
        self.files = files or {}
        self.auto_id = auto_id
        self.prefix = prefix
        self.initial = initial or {}
        self.error_class = error_class
        # Translators: This is the default suffix added to form field labels
        self.label_suffix = label_suffix if label_suffix is not None else _(':')
        self.empty_permitted = empty_permitted
        self._errors = None  # Stores the errors after clean() has been called.
        self._changed_data = None

        # The base_fields class attribute is the *class-wide* definition of
        # fields. Because a particular *instance* of the class might want to
        # alter self.fields, we create self.fields here by copying base_fields.
        # Instances should always modify self.fields; they should not modify
        # self.base_fields.
        self.fields = copy.deepcopy(self.base_fields)
        self._bound_fields_cache = {} 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:25,代碼來源:forms.py

示例3: clean

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def clean(self):
        if self.cleaned_data.get("fixed_deposit_account_no"):
            self.fixed_deposit_account = FixedDeposits.objects.filter(
                fixed_deposit_number=self.cleaned_data.get("fixed_deposit_account_no")).last()
        if not self.fixed_deposit_account:
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("No Fixed Deposit Accounts found with given a/c number")
            raise forms.ValidationError(errors)
        if self.fixed_deposit_account.status == "Paid":
            errors = self.errors.setdefault('message1', ErrorList())
            errors.append('Member Fixed Deposit already paid')
            raise forms.ValidationError(errors)
        elif self.fixed_deposit_account.status == 'Closed':
            errors = self._errors.setdefault("message1", ErrorList())
            errors.append("Member Fixed Deposit is Closed.")
            raise forms.ValidationError(errors)
        return self.cleaned_data 
開發者ID:MicroPyramid,項目名稱:micro-finance,代碼行數:19,代碼來源:forms.py

示例4: clean

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def clean(self, value):
        result = []
        errors = []
        for child_val in value:
            try:
                result.append(self.child_block.clean(child_val))
            except ValidationError as e:
                errors.append(ErrorList([e]))
            else:
                errors.append(None)

        if any(errors):
            # The message here is arbitrary - outputting error messages is delegated to the child blocks,
            # which only involves the 'params' list
            raise ValidationError('Validation error in ListBlock', params=errors)

        return result 
開發者ID:wagtail,項目名稱:wagtail,代碼行數:19,代碼來源:list_block.py

示例5: test_raises_custom_error_message

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def test_raises_custom_error_message(self):
        test_message = 'Not a valid library card number.'
        block = blocks.RegexBlock(regex=r'^[0-9]{3}$', error_messages={
            'invalid': test_message
        })

        with self.assertRaises(ValidationError) as context:
            block.clean("[/]")

        self.assertIn(test_message, context.exception.messages)

        html = block.render_form(
            "[/]",
            errors=ErrorList([ValidationError(test_message)]))

        self.assertIn(test_message, html) 
開發者ID:wagtail,項目名稱:wagtail,代碼行數:18,代碼來源:test_blocks.py

示例6: test_block_level_validation_renders_errors

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def test_block_level_validation_renders_errors(self):
        block = FooStreamBlock()

        post_data = {'stream-count': '2'}
        for i, value in enumerate(['bar', 'baz']):
            post_data.update({
                'stream-%d-deleted' % i: '',
                'stream-%d-order' % i: str(i),
                'stream-%d-type' % i: 'text',
                'stream-%d-value' % i: value,
            })

        block_value = block.value_from_datadict(post_data, {}, 'stream')
        with self.assertRaises(ValidationError) as catcher:
            block.clean(block_value)

        errors = ErrorList([
            catcher.exception
        ])

        self.assertInHTML(
            format_html('<div class="help-block help-critical">{}</div>', FooStreamBlock.error),
            block.render_form(block_value, prefix='stream', errors=errors)) 
開發者ID:wagtail,項目名稱:wagtail,代碼行數:25,代碼來源:test_blocks.py

示例7: __init__

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
                 label_suffix=None, empty_permitted=False, instance=None, request=None):
        initial = initial or {}
        self.request = request
        if instance:
            initial.update({
                'program_uuid': instance.condition.program_uuid,
                'benefit_type': instance.benefit.proxy().benefit_class_type,
                'benefit_value': instance.benefit.value,
            })
        super(ProgramOfferForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix,
                                               empty_permitted, instance)

        date_ui_class = {'class': 'add-pikaday'}
        self.fields['start_datetime'].widget.attrs.update(date_ui_class)
        self.fields['end_datetime'].widget.attrs.update(date_ui_class) 
開發者ID:edx,項目名稱:ecommerce,代碼行數:18,代碼來源:forms.py

示例8: __init__

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def __init__(  # pylint: disable=too-many-arguments
            self, data=None, files=None, auto_id='id_%s', prefix=None,
            initial=None, error_class=ErrorList, label_suffix=None,
            empty_permitted=False, instance=None, use_required_attribute=None,
            renderer=None):
        super().__init__(
            data, files, auto_id, prefix,
            initial, error_class, label_suffix,
            empty_permitted, instance, use_required_attribute,
            renderer,
        )

        for field in self.fields:
            self.fields[field].required = False
            # will cause BaseForm._clean_fields() to reuse the value
            # from self.initial (<-- self.instance) if not specified
            self.fields[field].disabled = field not in data 
開發者ID:kiwitcms,項目名稱:Kiwi,代碼行數:19,代碼來源:__init__.py

示例9: test_error_list

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def test_error_list(self):
        e = ErrorList()
        e.append('Foo')
        e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'}))

        self.assertIsInstance(e, list)
        self.assertIn('Foo', e)
        self.assertIn('Foo', forms.ValidationError(e))

        self.assertEqual(
            e.as_text(),
            '* Foo\n* Foobar'
        )

        self.assertEqual(
            e.as_ul(),
            '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
        )

        errors = e.get_json_data()
        self.assertEqual(
            errors,
            [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}]
        )
        self.assertEqual(json.dumps(errors), e.as_json()) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:27,代碼來源:test_forms.py

示例10: test_errorlist_override

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def test_errorlist_override(self):
        class DivErrorList(ErrorList):
            def __str__(self):
                return self.as_divs()

            def as_divs(self):
                if not self:
                    return ''
                return '<div class="errorlist">%s</div>' % ''.join(
                    '<div class="error">%s</div>' % e for e in self)

        class CommentForm(Form):
            name = CharField(max_length=50, required=False)
            email = EmailField()
            comment = CharField()

        data = {'email': 'invalid'}
        f = CommentForm(data, auto_id=False, error_class=DivErrorList)
        self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50"></p>
<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
<p>Email: <input type="email" name="email" value="invalid" required></p>
<div class="errorlist"><div class="error">This field is required.</div></div>
<p>Comment: <input type="text" name="comment" required></p>""") 
開發者ID:nesdis,項目名稱:djongo,代碼行數:25,代碼來源:test_forms.py

示例11: test_error_dict_copy

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def test_error_dict_copy(self):
        e = ErrorDict()
        e['__all__'] = ErrorList([
            ValidationError(
                message='message %(i)s',
                params={'i': 1},
            ),
            ValidationError(
                message='message %(i)s',
                params={'i': 2},
            ),
        ])

        e_copy = copy.copy(e)
        self.assertEqual(e, e_copy)
        self.assertEqual(e.as_data(), e_copy.as_data())

        e_deepcopy = copy.deepcopy(e)
        self.assertEqual(e, e_deepcopy)
        self.assertEqual(e.as_data(), e_copy.as_data()) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:22,代碼來源:test_utils.py

示例12: test_error_class

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def test_error_class(self):
        '''
        Test the type of Formset and Form error attributes
        '''
        Formset = modelformset_factory(User, fields="__all__")
        data = {
            'form-TOTAL_FORMS': '2',
            'form-INITIAL_FORMS': '0',
            'form-MAX_NUM_FORMS': '0',
            'form-0-id': '',
            'form-0-username': 'apollo13',
            'form-0-serial': '1',
            'form-1-id': '',
            'form-1-username': 'apollo13',
            'form-1-serial': '2',
        }
        formset = Formset(data)
        # check if the returned error classes are correct
        # note: formset.errors returns a list as documented
        self.assertIsInstance(formset.errors, list)
        self.assertIsInstance(formset.non_form_errors(), ErrorList)
        for form in formset.forms:
            self.assertIsInstance(form.errors, ErrorDict)
            self.assertIsInstance(form.non_field_errors(), ErrorList) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:26,代碼來源:tests.py

示例13: process_metadata

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def process_metadata(form_cls, request, helper):
    form = form_cls()

    if 'action_save' not in request.POST:
        return form

    form = form_cls(request.POST)

    if not form.is_valid():
        return form

    try:
        data = form_cls.processor(form)
    except Exception:
        errors = form._errors.setdefault('__all__', ErrorList())
        errors.append('Failed to parse provided SAML2 metadata')
        return form

    saml_form = SAMLForm(data)
    if not saml_form.is_valid():
        field_errors = ['%s: %s' % (k, ', '.join([force_text(i) for i in v])) for k, v in saml_form.errors.items()]
        error_list = ', '.join(field_errors)

        errors = form._errors.setdefault('__all__', ErrorList())
        errors.append(u'Invalid metadata: {}'.format(error_list))
        return form

    helper.bind_state('idp', data)

    # Data is bound, do not respond with a form to signal the nexts steps
    return None 
開發者ID:getsentry,項目名稱:sentry-auth-saml2,代碼行數:33,代碼來源:forms.py

示例14: new_automation

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def new_automation(request, alert_type):
    alert_type = get_object_or_404(AlertType, slug=alert_type, unit__in=request.units)

    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            if AlertEmailTemplate.objects.filter(alerttype=alert_type, hidden=False, threshold=form.cleaned_data['threshold']).count() > 0:
                errors = form._errors.setdefault("threshold", ErrorList())
                errors.append('An e-mail with this threshold already exists.' )
            else:
                f = form.save(commit=False)
                f.alerttype = alert_type
                f.created_by = request.user.username            
                f.save()
                messages.success(request, "Created new automated email for %s." % alert_type.code)
                l = LogEntry(userid=request.user.username,
                      description="Created new automated email %s." % alert_type.code,
                      related_object=form.instance)
                l.save()            
                return HttpResponseRedirect(reverse('alerts.views.view_automation', kwargs={'alert_type':alert_type.slug}))
    else:
        form = EmailForm()

    sample_alert = Alert.objects.filter(alerttype=alert_type, hidden=False)[0]

    email_tags = [
        ("person.name","The name of the student that has triggered the alert"),
        ("person.first_name", "The first name of the student."),
        ("person.last_name", "The last name of the student."),
        ("person.middle_name", "The middle name of the student."),
        ("person.emplid", "The student's emplid."),
        ("person.email", "The student's email."),
        ("person.title", "The student's title."),
        ("description","The description of the alert.")
    ]
    
    for k, v in sample_alert.details.items():
        email_tags.append( ("details."+k, "For example, (" + str(v) + ")") )
    
    return render(request, 'alerts/new_automation.html', { 'alert_type':alert_type, 'form': form, 'email_tags':email_tags }) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:42,代碼來源:views.py

示例15: manage_promises

# 需要導入模塊: from django.forms import utils [as 別名]
# 或者: from django.forms.utils import ErrorList [as 別名]
def manage_promises(request, grad_slug):
    grad = get_object_or_404(GradStudent, slug = grad_slug)
    promises = Promise.objects.filter(student=grad).order_by('start_semester__name')
    
    if request.method == 'POST':
        form = PromiseForm(request.POST)
        if form.is_valid():
            try:
                promise = promises.get(end_semester=form.cleaned_data['end_semester'], removed=False)
            except Promise.DoesNotExist:
                promise = None

            if promise != None:
                form._errors['end_semester'] = ErrorList(["A Promise for this semester already exists."])
            else:
                promise = form.save(commit=False)
                promise.student = grad
                promise.save()
                messages.success(request, "Promise for %s sucessfully saved." % (grad))
                l = LogEntry(userid=request.user.username, 
                  description="added promise of $%f for %s" % (promise.amount, grad.slug),
                  related_object=promise )
                l.save()
                
                return HttpResponseRedirect(reverse('grad:manage_promises', kwargs={'grad_slug':grad.slug}))
    else:
        form = PromiseForm(initial={'student':grad, 'start_semester':Semester.get_semester(), 'end_semester':Semester.get_semester(), 'amount':'0.00'})
    
    context = {
                'grad':grad,
                'form': form,
                'promises': promises,
                'can_edit': True,
              }
    return render(request, 'grad/manage_promises.html', context) 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:37,代碼來源:manage_promises.py


注:本文中的django.forms.utils.ErrorList方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。