本文整理汇总了Python中django.forms.utils.ErrorList类的典型用法代码示例。如果您正苦于以下问题:Python ErrorList类的具体用法?Python ErrorList怎么用?Python ErrorList使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ErrorList类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clean
def clean(self, value):
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'])
else:
return []
else:
raise ValidationError(self.error_messages['invalid'])
for field_value in value:
try:
clean_data.append(self.contained_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.
errors.extend(e.messages)
if self.contained_field.required:
self.contained_field.required = False
if errors:
raise ValidationError(errors)
self.validate(clean_data)
self.run_validators(clean_data)
return clean_data
示例2: clean
def clean(self, value):
"""
We clean every subwidget.
"""
clean_data = []
errors = ErrorList()
is_empty = not value or not [v for v in value if v not in self.empty_values]
if is_empty and not self.required:
return []
if is_empty and self.required:
raise ValidationError(self.error_messages['required'])
if value and not isinstance(value, (list, tuple)):
raise ValidationError(self.error_messages['invalid'])
for field_value, checkbox_value in value:
try:
clean_data.append([self.contained_field.clean(field_value), checkbox_value])
except ValidationError as e:
errors.extend(e.messages)
# FIXME: copy paste from above
if self.contained_field.required:
self.contained_field.required = False
if errors:
raise ValidationError(errors)
self.validate(clean_data)
self.run_validators(clean_data)
return clean_data
示例3: clean_deck_order
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
示例4: get_error_titles
def get_error_titles(self):
errors = ErrorList()
for form in self.formsets:
for item in form.errors:
if item:
errors.extend(item)
return errors
示例5: validation_error_as_text
def validation_error_as_text(error):
"""
Given a ValidationError object, return a string representing the errors.
"""
try:
ed = ErrorDict(error.message_dict)
return ed.as_text()
except AttributeError:
el = ErrorList(error.messages)
return el.as_text()
示例6: login_view
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),
)
示例7: clean
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
示例8: post
def post(self, request, *args, **kwargs):
if self.async_response is not None:
return self.async_response
if self.subscription_form.is_valid():
try:
subscription = self.subscription_form.create_subscription()
return HttpResponseRedirect(
reverse(EditSubscriptionView.urlname, args=(subscription.id,))
)
except NewSubscriptionError as e:
errors = ErrorList()
errors.extend([e.message])
self.subscription_form._errors.setdefault(NON_FIELD_ERRORS, errors)
return self.get(request, *args, **kwargs)
示例9: clean
def clean(self, value):
clean_data = {}
errors = ErrorList()
if not value or isinstance(value, dict):
if not value or not [
v for v in value.values() if v not in self.empty_values
]:
if self.required:
raise ValidationError(self.error_messages['required'])
else:
return {}
else:
raise ValidationError(self.error_messages['invalid'])
# sort out required => at least one element must be in there
for key, val in value.items():
# ignore empties. Can they even come up here?
if key in self.empty_values and val in self.empty_values:
continue
try:
val = self.contained_field.clean(val)
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.
errors.extend(e.messages)
try:
self._validate_key(key)
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.
errors.extend(e.messages)
clean_data[key] = val
if self.contained_field.required:
self.contained_field.required = False
if errors:
raise ValidationError(errors)
self.validate(clean_data)
self.run_validators(clean_data)
return clean_data
示例10: clean
def clean(self, value):
"""
This is a copy of MultiValueField.clean() with a BUGFIX:
- if self.required and field_value in validators.EMPTY_VALUES:
+ if field.required and field_value in validators.EMPTY_VALUES:
"""
try:
from django.forms.utils import ErrorList
except ImportError:
from django.forms.util import ErrorList
from django.core import validators
from django.core.exceptions import ValidationError
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 validators.EMPTY_VALUES]:
if self.required:
raise ValidationError(self.error_messages['required'])
else:
return self.compress(value)
else:
raise ValidationError(self.error_messages['invalid'])
for i, field in enumerate(self.fields):
try:
field_value = value[i]
except IndexError:
field_value = None
if field.required and field_value in validators.EMPTY_VALUES:
raise ValidationError(self.error_messages['required'])
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.
errors.extend(e.messages)
if errors:
raise ValidationError(errors)
out = self.compress(clean_data)
self.validate(out)
self.run_validators(out)
return out
示例11: clean
def clean(self, value):
# Get the value
# Totally replaced validation.
clean_data = []
errors = ErrorList()
# Only the visible field is required.
radio_value = value[0]
field_visible = [False] * len(self.fields)
field_visible[0] = True
if radio_value is None:
# radio_value is None when models are deleted in formsets
out = ''
else:
field_visible[self.url_type_registry.index(radio_value) + 1] = True
# The validators only fire for visible fields.
for i, field in enumerate(self.fields):
try:
field_value = value[i]
except IndexError:
field_value = None
if not field_visible[i]:
clean_data.append(None)
continue
if self.required and field_value in validators.EMPTY_VALUES:
raise ValidationError(self.error_messages['required'])
try:
clean_data.append(field.clean(field_value))
except ValidationError as e:
errors.extend(e.messages) # Collect all widget errors
if errors:
raise ValidationError(errors)
out = self.compress(clean_data)
self.validate(out)
return out
示例12: account_login
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})
示例13: test_error_list_html_safe
def test_error_list_html_safe(self):
e = ErrorList(['Invalid username.'])
self.assertTrue(hasattr(ErrorList, '__html__'))
self.assertEqual(force_text(e), e.__html__())
示例14: clean
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)
示例15: hidden_field_errors
def hidden_field_errors(form):
hidden_field_errors = ErrorList()
for field in form.hidden_fields():
hidden_field_errors.extend(field.errors)
return hidden_field_errors