本文整理汇总了Python中django.core.exceptions.NON_FIELD_ERRORS属性的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NON_FIELD_ERRORS属性的具体用法?Python exceptions.NON_FIELD_ERRORS怎么用?Python exceptions.NON_FIELD_ERRORS使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类django.core.exceptions
的用法示例。
在下文中一共展示了exceptions.NON_FIELD_ERRORS属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: analyze_password
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def analyze_password(self, password_field_value):
insecure, howmuch = is_password_compromised(password_field_value)
if insecure and howmuch > 99:
self.add_error(NON_FIELD_ERRORS, ValidationError(_(
"The password selected by you is too insecure. "
"Such combination of characters is very well-known to cyber-criminals."),
code='compromised_password'))
self.add_error(self.analyze_password_field, _("Choose a less easily guessable password."))
elif insecure and howmuch > 1:
self.add_error(NON_FIELD_ERRORS, ValidationError(_(
"The password selected by you is not very secure. "
"Such combination of characters is known to cyber-criminals."),
code='compromised_password'))
self.add_error(self.analyze_password_field, _("Choose a less easily guessable password."))
if insecure:
auth_log.warning(
"Password with HIBP count {:d} selected in {}.".format(howmuch, self.__class__.__name__),
extra={'request': self.view_request} if hasattr(self, 'view_request') else None,
)
示例2: validation_error
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def validation_error(request, message, form, buttons=None):
if not form.non_field_errors():
# just output the generic "there were validation errors" message, and leave
# the per-field highlighting to do the rest
detail = ''
else:
# display the full list of field and non-field validation errors
all_errors = []
for field_name, errors in form.errors.items():
if field_name == NON_FIELD_ERRORS:
prefix = ''
else:
try:
field_label = form[field_name].label
except KeyError:
field_label = field_name
prefix = "%s: " % field_label
for error in errors:
all_errors.append(prefix + error)
errors_html = format_html_join('\n', '<li>{}</li>', ((e,) for e in all_errors))
detail = format_html("""<ul class="errorlist">{}</ul>""", errors_html)
return messages.error(request, render(message, buttons, detail=detail))
示例3: non_field_errors
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def non_field_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
are none.
"""
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
示例4: test_form_valid_invalid_inputs_error
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def test_form_valid_invalid_inputs_error(self, form_invalid, form_valid):
request, _, _ = self.build_request('GET', {})
form = MagicMock()
view = InvalidInputsErrorView()
view.request = request
view.form_valid(form)
form_valid.assert_not_called()
form_invalid.assert_called_once_with(form)
form.add_error.assert_has_calls([
call(NON_FIELD_ERRORS, [non_field_error]),
call('field1', [field1_error])
], any_order=True)
示例5: non_field_errors
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def non_field_errors(self):
"""
Return an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Return an empty ErrorList if there
are none.
"""
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
示例6: post
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def post(self, request, *args, **kwargs):
place = self.get_object()
place_data = serializers.serialize('json', [place], fields=PlaceForm._meta.fields)
place_data = json.loads(place_data)[0]['fields']
owner_data = serializers.serialize('json', [place.owner], fields=ProfileForm._meta.fields)
owner_data = json.loads(owner_data)[0]['fields']
owner_form = ProfileForm(data=owner_data, instance=place.owner)
place_form = PlaceForm(data=place_data, instance=place)
data_correct = all([owner_form.is_valid(), place_form.is_valid()]) # We want both validations.
viewresponse = {'result': data_correct}
if not data_correct:
viewresponse['err'] = OrderedDict()
data_problems = set()
for form in [owner_form, place_form]:
viewresponse['err'].update({
str(form.fields[field_name].label) : list(field_errs) # noqa: E203
for field_name, field_errs
in [(k, set(err for err in v if err)) for k, v in form.errors.items()]
if field_name != NON_FIELD_ERRORS and len(field_errs)
})
data_problems.update(form.errors.get(NON_FIELD_ERRORS, []))
if len(data_problems):
viewresponse['err'+NON_FIELD_ERRORS] = list(data_problems)
else:
place.set_check_status(self.request.user)
if request.is_ajax():
return JsonResponse(viewresponse)
else:
return TemplateResponse(
request,
self.template_names[data_correct],
context={'view': self, 'place': place, 'result': viewresponse}
)
示例7: validate_unique
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def validate_unique(self):
'''This clean method will check for unique_together condition'''
# Collect unique_checks and to run from all the forms.
all_unique_checks = set()
all_date_checks = set()
forms_to_delete = self.deleted_forms
valid_forms = [form for form in self.forms if form.is_valid() and form not in forms_to_delete]
for form in valid_forms:
unique_checks, date_checks = form.instance._get_unique_checks()
all_unique_checks.update(unique_checks)
all_date_checks.update(date_checks)
errors = []
# Do each of the unique checks (unique and unique_together)
for uclass, unique_check in all_unique_checks:
seen_data = set()
for form in valid_forms:
# Get the data for the set of fields that must be unique among the forms.
row_data = (
field if field in self.unique_fields else form.cleaned_data[field]
for field in unique_check if field in form.cleaned_data
)
# Reduce Model instances to their primary key values
row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d
for d in row_data)
if row_data and None not in row_data:
# if we've already seen it then we have a uniqueness failure
if row_data in seen_data:
# poke error messages into the right places and mark
# the form as invalid
errors.append(self.get_unique_error_message(unique_check))
form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
# remove the data from the cleaned_data dict since it was invalid
for field in unique_check:
if field in form.cleaned_data:
del form.cleaned_data[field]
# mark the data as seen
seen_data.add(row_data)
if errors:
raise ValidationError(errors)
示例8: __init__
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def __init__(self, block_errors=None, non_block_errors=None):
params = {}
if block_errors:
params.update(block_errors)
if non_block_errors:
params[NON_FIELD_ERRORS] = non_block_errors
super().__init__(
'Validation error in StreamBlock', params=params)
示例9: render_form
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def render_form(self, value, prefix='', errors=None):
error_dict = {}
if errors:
if len(errors) > 1:
# We rely on StreamBlock.clean throwing a single
# StreamBlockValidationError with a specially crafted 'params'
# attribute that we can pull apart and distribute to the child
# blocks
raise TypeError('StreamBlock.render_form unexpectedly received multiple errors')
error_dict = errors.as_data()[0].params
# value can be None when the StreamField is in a formset
if value is None:
value = self.get_default()
# drop any child values that are an unrecognised block type
valid_children = [child for child in value if child.block_type in self.child_blocks]
list_members_html = [
self.render_list_member(child.block_type, child.value, "%s-%d" % (prefix, i), i,
errors=error_dict.get(i), id=child.id)
for (i, child) in enumerate(valid_children)
]
return render_to_string('wagtailadmin/block_forms/stream.html', {
'prefix': prefix,
'help_text': getattr(self.meta, 'help_text', None),
'list_members_html': list_members_html,
'child_blocks': self.sorted_child_blocks(),
'header_menu_prefix': '%s-before' % prefix,
'block_errors': error_dict.get(NON_FIELD_ERRORS),
'classname': getattr(self.meta, 'form_classname', None),
})
示例10: _update_errors
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def _update_errors(self, message_dict):
for k, v in message_dict.items():
if k != NON_FIELD_ERRORS:
self._errors.setdefault(k, self.error_class()).extend(v)
# Remove the data from the cleaned_data dict since it was invalid
if k in self.cleaned_data:
del self.cleaned_data[k]
if NON_FIELD_ERRORS in message_dict:
messages = message_dict[NON_FIELD_ERRORS]
self._errors.setdefault(NON_FIELD_ERRORS, self.error_class()).extend(messages)
示例11: _post_clean
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def _post_clean(self):
opts = self._meta
# Update the model instance with self.cleaned_data.
self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
exclude = self._get_validation_exclusions()
# Foreign Keys being used to represent inline relationships
# are excluded from basic field value validation. This is for two
# reasons: firstly, the value may not be supplied (#12507; the
# case of providing new values to the admin); secondly the
# object being referred to may not yet fully exist (#12749).
# However, these fields *must* be included in uniqueness checks,
# so this can't be part of _get_validation_exclusions().
for f_name, field in self.fields.items():
if isinstance(field, InlineForeignKeyField):
exclude.append(f_name)
# Clean the model instance's fields.
try:
self.instance.clean_fields(exclude=exclude)
except ValidationError as e:
self._update_errors(e.message_dict)
# Call the model instance's clean method.
try:
self.instance.clean()
except ValidationError as e:
self._update_errors({NON_FIELD_ERRORS: e.messages})
# Validate uniqueness if needed.
if self._validate_unique:
self.validate_unique()
示例12: __init__
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def __init__(self, *args, **kwargs):
super(RulesetChoiceForm, self).__init__(*args, **kwargs)
ruleset_list = Ruleset.objects.all()
self.fields['rulesets'].queryset = ruleset_list
if hasattr(self, 'rulesets_label'):
self.fields['rulesets'].label = self.rulesets_label
if not len(ruleset_list):
if not (isinstance(self, AddSourceForm) or isinstance(self, AddPublicSourceForm)):
self.errors[NON_FIELD_ERRORS] = ['Please create a ruleset first']
self.fields.pop('rulesets')
示例13: validate
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def validate(self, attrs):
attrs = super(PaymentMethodSerializer, self).validate(attrs)
if self.instance:
if self.instance.canceled:
raise ValidationError(
'You cannot update a canceled payment method.'
)
# Run model clean and handle ValidationErrors
try:
# Use the existing instance to avoid unique field errors
payment_method = self.instance
payment_method_dict = payment_method.__dict__.copy()
for attribute, value in attrs.items():
setattr(payment_method, attribute, value)
payment_method.full_clean()
# Revert changes to existing instance
payment_method.__dict__ = payment_method_dict
except ValidationError as e:
errors = e.error_dict
non_field_errors = errors.pop(NON_FIELD_ERRORS, None)
if non_field_errors:
errors['non_field_errors'] = [
error for sublist in non_field_errors for error in sublist
]
raise serializers.ValidationError(errors)
return attrs
示例14: django_to_drf_validation_error
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def django_to_drf_validation_error(django_validation_error,
default_errors_key=None):
try:
errors = django_validation_error.message_dict
except AttributeError:
errors = django_validation_error.messages
if default_errors_key:
errors = {default_errors_key: errors}
else:
non_field_errors = errors.pop(NON_FIELD_ERRORS, None)
if non_field_errors:
errors[default_errors_key or api_settings.NON_FIELD_ERRORS_KEY] = non_field_errors
raise serializers.ValidationError(errors)
示例15: clean
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import NON_FIELD_ERRORS [as 别名]
def clean(self):
super(BillingDocumentBase, self).clean()
# The only change that is allowed if the document is in issued state
# is the state chage from issued to paid
# !! TODO: If _last_state == 'issued' and self.state == 'paid' || 'canceled'
# it should also be checked that the other fields are the same bc.
# right now a document can be in issued state and someone could
# send a request which contains the state = 'paid' and also send
# other changed fields and the request would be accepted bc. only
# the state is verified.
if self._last_state == self.STATES.ISSUED and\
self.state not in [self.STATES.PAID, self.STATES.CANCELED]:
msg = 'You cannot edit the document once it is in issued state.'
raise ValidationError({NON_FIELD_ERRORS: msg})
if self._last_state == self.STATES.CANCELED:
msg = 'You cannot edit the document once it is in canceled state.'
raise ValidationError({NON_FIELD_ERRORS: msg})
# If it's in paid state => don't allow any changes
if self._last_state == self.STATES.PAID:
msg = 'You cannot edit the document once it is in paid state.'
raise ValidationError(msg)
if self.transactions.exclude(currency=self.transaction_currency).exists():
message = 'There are unfinished transactions of this document that use a ' \
'different currency.'
raise ValidationError({'transaction_currency': message})