本文整理汇总了Python中django.forms.util.ErrorList类的典型用法代码示例。如果您正苦于以下问题:Python ErrorList类的具体用法?Python ErrorList怎么用?Python ErrorList使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ErrorList类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clean
def clean(self, value):
"""
Only the default language should be required.
"""
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([])
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 i == 0 and 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:
# 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
示例2: clean
def clean(self, value):
'''\
value is assumed to be a dictionary of values with keys corresponding
to the ones in self.subfields. Each value is validated against it's
corresponding field.
'''
clean_data = {}
errors = ErrorList()
if value is None:
return value
if not isinstance(value, dict):
raise ValidationError(self.error_messages['invalid'])
for fieldname, field in self.subfields.items():
if not fieldname in value.keys():
if field.required:
raise ValidationError(field.error_messages['required'])
else:
continue
try:
clean_data[fieldname] = field.clean(value[fieldname])
except ValidationError, e:
errors.extend(e.messages)
示例3: clean
def clean(self, value):
clean_data = []
errors = ErrorList()
if value in validators.EMPTY_VALUES and self.required:
raise ValidationError(self.error_messages['required'])
for i, field in enumerate(self.fields):
try:
field_value = value[i]
except IndexError:
field_value = None
if field_value in validators.EMPTY_VALUES:
if (self.required and not self.optional):
raise ValidationError(self.error_messages['required'])
else:
field_value = field_value
try:
clean_data.append(field.clean(field_value))
except ValidationError, e:
errors.extend(e.messages)
if i == len(self.fields) and len(clean_data) == 0:
raise ValidationError(self.error_messages['optional_required'])
示例4: clean
def clean(self, value):
""" Take a tuple of fields_valie(dict) and json_value(str) from JSONWidget """
fields_value, json_value = value
errors = ErrorList()
# Clear json value
if isinstance(json_value, basestring):
try:
json_value = loads(json_value)
except ValueError:
json_value = None
errors.append(_(u"JSON Field: Enter valid JSON"))
if json_value != None and not isinstance(json_value, dict):
errors.append(_(u"JSON Field: Must be a dict"))
# Clear fields
assert isinstance(fields_value, dict)
if json_value:
merge_dict(fields_value, json_value)
def _clean(f, _values):
for k, v in iterhelper(f):
if isinstance(v, (dict, tuple, list)):
_clean(v, _values.get(k, {}))
else:
try:
tmp = _values.get(k, None)
v.clean(tmp)
_values[k] = v.to_python(tmp)
except FormValidationError, e:
errors.extend(
map(lambda x, y: x + y, [u"%s %s: " % (_("Field"), k)] * len(e.messages), e.messages)
)
示例5: clean_sub_fields
def clean_sub_fields(self, value):
"""'value' being the list of the values of the subfields, validate
each subfield."""
clean_data = []
errors = ErrorList()
# Remove the field corresponding to the SKIP_CHECK_NAME boolean field
# if required.
fields = self.fields if not self.skip_check else self.fields[:-1]
for index, field in enumerate(fields):
try:
field_value = value[index]
except IndexError:
field_value = None
# Check the field's 'required' field instead of the global
# 'required' field to allow subfields to be required or not.
if field.required and field_value in validators.EMPTY_VALUES:
errors.append(
'%s: %s' % (field.label, self.error_messages['required']))
continue
try:
clean_data.append(field.clean(field_value))
except ValidationError, 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(
['%s: %s' % (field.label, message)
for message in e.messages])
示例6: lib_artist
def lib_artist(request, artist_name):
artist_name_comma = Artist.commafy(artist_name)
artist = get_object_or_none(Artist, name=artist_name_comma)
if (artist is None):
artist = get_object_or_none(Artist, name=artist_name)
errors = ErrorList()
albums = []
similar_artists = []
artist_art = ''
api = PyLastFm()
art_api = EchoNest()
if artist is not None:
albums = Album.objects.filter(artist=artist).order_by("-date_released")
if albums.count() > 0:
lfm_artist = get_last_fm_artist_name(artist)
if lfm_artist:
similar_artists = [similar for similar in api.get_similar_artists(lfm_artist)
if Artist.objects.filter(name__iexact=similar).count() > 0 or
Artist.objects.filter(name__iexact=Artist.commafy(similar)).count() > 0
]
artist_art = art_api.get_artist_art(lfm_artist)
else:
errors.append('The artist could not be found by Last.Fm')
return render_to_response('artist.html', {
'errors': errors,
'albums': albums,
'artist': artist,
'artist_art': artist_art,
'similar_artists': similar_artists,
}, context_instance=RequestContext(request))
示例7: form_valid
def form_valid(self, form):
with transaction.commit_manually():
try:
super(ItemCreate, self).form_valid(form)
except ValidationError as e:
transaction.rollback()
errors = ErrorList()
for error in e.messages:
errors.append(error)
errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)
return super(ItemCreate, self).form_invalid(form)
context = self.get_context_data()
itemimage_form = context['itemimage_formset']
if itemimage_form.is_valid():
itemimage_form.save()
transaction.commit()
return redirect(self.get_success_url())
else:
transaction.rollback()
return self.render_to_response(
self.get_context_data(form=form)
)
示例8: 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'])
field = self.field_type(required=self.required)
for field_value in value:
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 field.required:
field.required = False
if errors:
raise ValidationError(errors)
self.validate(clean_data)
self.run_validators(clean_data)
return clean_data
示例9: 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 validators.EMPTY_VALUES]:
if self.required:
raise ValidationError(self.error_messages["required"])
else:
return self.compress([])
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 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, 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)
示例10: 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
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, e:
errors.extend(e.messages) # Collect all widget errors
示例11: _login_view
def _login_view(request):
"""Standard Django login plus lowercases the login email(username)"""
if request.method == "POST":
redirect_to = request.REQUEST.get('next', False)
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:
login(request, new_user)
if redirect_to:
return HttpResponseRedirect(redirect_to)
else:
return HttpResponseRedirect(reverse("seed:home"))
else:
errors = ErrorList()
errors = form._errors.setdefault(NON_FIELD_ERRORS, errors)
errors.append('Username and/or password were invalid.')
else:
form = LoginForm()
return locals()
示例12: 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, 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
data_field = self.field_type(**self.field_kwargs)
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 = data_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 data_field.required:
data_field.required = False
if errors:
raise ValidationError(errors)
self.validate(clean_data)
self.run_validators(clean_data)
return clean_data
示例13: 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(ManageBillingAccountView.urlname, args=(subscription.account.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)
示例14: lib_main
def lib_main(request):
albums = []
errors = ErrorList()
pager = Paginator([], 1)
selected_page = 1
form = None # it's our search form
# If a form was just submitted
if request.method == 'POST':
form = SearchForm(request.POST) # A form bound to the POST data
if form.is_valid():
# Use the form fields to search and filter albums from the db
albums = lib_main_filter_albums(form)
pager = Paginator(albums, form.cleaned_data['items_per_page'])
selected_page = int(form.cleaned_data['selected_page'])
page_list = [(str(x), str(x)) for x in pager.page_range][:100]
if len(page_list) is 0:
form.fields['selected_page'][('1', '1')]
else:
form.fields['selected_page'].choices = page_list
form.fields['selected_page'].initial = selected_page
else:
# Add all of the errors in the form.errors dict to our error list
errors.extend(chain.from_iterable(form.errors.values()))
form.save()
else:
form = SearchForm(initial={'artist': request.GET.get('artist'),
'album': request.GET.get('album'),
'label': request.GET.get('label'),
'year': request.GET.get('year'),
'genre': request.GET.get('genre'),
'stack': request.GET.get('stack'),
'selected_page': "1",
'items_per_page': "25",
})
form.fields['selected_page'].choices = [(str(x), str(x)) for x in pager.page_range][:100]
albums_page = []
try:
albums_page = pager.page(selected_page).object_list
except EmptyPage:
albums_page = pager.page(1).object_list
errors.append("That page is empty.")
return render_to_response('library.html', {
'form': form,
'albums': albums_page,
'errors': errors,
}, context_instance=RequestContext(request))
示例15: 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.REQUEST.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),
)