本文整理汇总了Python中django.forms.util.ErrorDict.items方法的典型用法代码示例。如果您正苦于以下问题:Python ErrorDict.items方法的具体用法?Python ErrorDict.items怎么用?Python ErrorDict.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.forms.util.ErrorDict
的用法示例。
在下文中一共展示了ErrorDict.items方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error
# 需要导入模块: from django.forms.util import ErrorDict [as 别名]
# 或者: from django.forms.util.ErrorDict import items [as 别名]
def error(self, request, status_code, error_dict=None):
"""
Return XML error response that includes a human readable error
message, application-specific errors and a machine readable
status code.
"""
from django.conf import settings
if not error_dict:
error_dict = ErrorDict()
response = HttpResponse(mimetype = self.mimetype)
response.status_code = status_code
xml = SimplerXMLGenerator(response, settings.DEFAULT_CHARSET)
xml.startDocument()
xml.startElement("django-error", {})
xml.addQuickElement(name="error-message", contents='%d %s' % (status_code, STATUS_CODE_TEXT[status_code]))
xml.addQuickElement(name="status-code", contents=str(status_code))
if error_dict:
xml.startElement("model-errors", {})
for (model_field, errors) in error_dict.items():
for error in errors:
xml.addQuickElement(name=model_field, contents=error)
xml.endElement("model-errors")
xml.endElement("django-error")
xml.endDocument()
return response
示例2: NgModelFormMixin
# 需要导入模块: from django.forms.util import ErrorDict [as 别名]
# 或者: from django.forms.util.ErrorDict import items [as 别名]
class NgModelFormMixin(NgFormBaseMixin):
"""
Add this NgModelFormMixin to every class derived from ``forms.Form``, if that custom ``Form``
shall be managed through an Angular controller.
It adds attributes ``ng-model``, and optionally ``ng-change``, ``ng-class`` and ``ng-style``
to each of your input fields.
If form validation fails, the ErrorDict is rewritten in a way, so that the Angular controller
can access the error strings using the same key values as for its models.
"""
add_djng_error = False
def __init__(self, data=None, *args, **kwargs):
self.scope_prefix = kwargs.pop('scope_prefix', getattr(self, 'scope_prefix', None))
self.ng_directives = {}
for key in list(kwargs.keys()):
if key.startswith('ng_'):
fmtstr = kwargs.pop(key)
self.ng_directives[key.replace('_', '-')] = fmtstr
if hasattr(self, 'Meta') and hasattr(self.Meta, 'ng_models'):
if not isinstance(getattr(self.Meta, 'ng_models'), list):
raise TypeError('Meta.ng_model is not of type list')
elif 'ng-model' not in self.ng_directives:
self.ng_directives['ng-model'] = '%(model)s'
self.prefix = kwargs.get('prefix')
if self.prefix and data:
data = dict((self.add_prefix(name), value) for name, value in data.get(self.prefix).items())
super(NgModelFormMixin, self).__init__(data, *args, **kwargs)
if self.scope_prefix == self.form_name:
raise ValueError("The form's name may not be identical with its scope_prefix")
def _post_clean(self):
"""
Rewrite the error dictionary, so that its keys correspond to the model fields.
"""
super(NgModelFormMixin, self)._post_clean()
if self._errors and self.prefix:
self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
def get_initial_data(self):
"""
Return a dictionary specifying the defaults for this form. This dictionary can be used to
inject the initial values for an Angular controller using the directive:
``ng-init={{ thisform.get_initial_data|js|safe }}``.
"""
data = {}
ng_models = hasattr(self, 'Meta') and getattr(self.Meta, 'ng_models', []) or []
for name, field in self.fields.items():
if 'ng-model' in self.ng_directives or name in ng_models:
data[name] = self.initial and self.initial.get(name) or field.initial
return data
def get_field_errors(self, field):
errors = super(NgModelFormMixin, self).get_field_errors(field)
if field.is_hidden:
return errors
identifier = format_html('{0}.{1}', self.form_name, field.name)
errors.append(SafeTuple((identifier, self.field_error_css_classes, '$pristine', '$message', 'invalid', '$message')))
return errors
def non_field_errors(self):
errors = super(NgModelFormMixin, self).non_field_errors()
errors.append(SafeTuple((self.form_name, self.form_error_css_classes, '$pristine', '$message', 'invalid', '$message')))
return errors
def get_widget_attrs(self, bound_field):
attrs = super(NgModelFormMixin, self).get_widget_attrs(bound_field)
identifier = self.add_prefix(bound_field.name)
ng = {
'name': bound_field.name,
'identifier': identifier,
'model': self.scope_prefix and ('%s.%s' % (self.scope_prefix, identifier)) or identifier
}
if hasattr(self, 'Meta') and bound_field.name in getattr(self.Meta, 'ng_models', []):
attrs['ng-model'] = ng['model']
for key, fmtstr in self.ng_directives.items():
attrs[key] = fmtstr % ng
return attrs
示例3: NgModelFormMixin
# 需要导入模块: from django.forms.util import ErrorDict [as 别名]
# 或者: from django.forms.util.ErrorDict import items [as 别名]
class NgModelFormMixin(NgFormBaseMixin):
"""
Add this NgModelFormMixin to every class derived from forms.Form, if
you want to manage that form through an Angular controller.
It adds attributes ng-model, and optionally ng-change, ng-class and ng-style
to each of your input fields.
If form validation fails, the ErrorDict is rewritten in a way, so that the
Angular controller can access the error strings using the same key values as
for its models.
"""
def __init__(self, data=None, *args, **kwargs):
self.scope_prefix = kwargs.pop("scope_prefix", getattr(self, "scope_prefix", None))
self.ng_directives = {}
for key in list(kwargs.keys()):
if key.startswith("ng_"):
fmtstr = kwargs.pop(key)
self.ng_directives[key.replace("_", "-")] = fmtstr
if hasattr(self, "Meta") and hasattr(self.Meta, "ng_models"):
if not isinstance(getattr(self.Meta, "ng_models"), list):
raise TypeError("Meta.ng_model is not of type list")
elif "ng-model" not in self.ng_directives:
self.ng_directives["ng-model"] = "%(model)s"
self.prefix = kwargs.get("prefix")
if self.prefix and data:
data = dict((self.add_prefix(name), value) for name, value in data.get(self.prefix).items())
super(NgModelFormMixin, self).__init__(data, *args, **kwargs)
if self.scope_prefix == self.form_name:
raise ValueError("The form's name may not be identical with its scope_prefix")
def _post_clean(self):
"""
Rewrite the error dictionary, so that its keys correspond to the model fields.
"""
super(NgModelFormMixin, self)._post_clean()
if self._errors and self.prefix:
self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
def get_initial_data(self):
"""
Return a dictionary specifying the defaults for this form. This dictionary can be used to
inject the initial values for an Angular controller using the directive:
``ng-init={{ thisform.get_initial_data|js|safe }}``.
"""
data = {}
ng_models = hasattr(self, "Meta") and getattr(self.Meta, "ng_models", []) or []
for name, field in self.fields.items():
if "ng-model" in self.ng_directives or name in ng_models:
data[name] = self.initial and self.initial.get(name) or field.initial
return data
def get_field_errors(self, field):
errors = super(NgModelFormMixin, self).get_field_errors(field)
if field.is_hidden:
return errors
identifier = format_html("{0}.{1}", self.form_name, field.name)
errors.append(
SafeTuple((identifier, self.field_error_css_classes, "$pristine", "$message", "invalid", "$message"))
)
return errors
def non_field_errors(self):
errors = super(NgModelFormMixin, self).non_field_errors()
errors.append(
SafeTuple((self.form_name, self.form_error_css_classes, "$pristine", "$message", "invalid", "$message"))
)
return errors
def get_widget_attrs(self, bound_field):
identifier = self.add_prefix(bound_field.name)
ng = {
"name": bound_field.name,
"identifier": identifier,
"model": self.scope_prefix and ("%s.%s" % (self.scope_prefix, identifier)) or identifier,
}
attrs = {}
if hasattr(self, "Meta") and bound_field.name in getattr(self.Meta, "ng_models", []):
attrs["ng-model"] = ng["model"]
for key, fmtstr in self.ng_directives.items():
attrs[key] = fmtstr % ng
return attrs
示例4: NgModelFormMixin
# 需要导入模块: from django.forms.util import ErrorDict [as 别名]
# 或者: from django.forms.util.ErrorDict import items [as 别名]
class NgModelFormMixin(NgFormBaseMixin):
"""
Add this NgModelFormMixin to every class derived from forms.Form, if
you want to manage that form through an Angular controller.
It adds attributes ng-model, and optionally ng-change, ng-class and ng-style
to each of your input fields.
If form validation fails, the ErrorDict is rewritten in a way, so that the
Angular controller can access the error strings using the same key values as
for its models.
"""
def __init__(self, *args, **kwargs):
self.scope_prefix = kwargs.pop('scope_prefix', None)
if hasattr(self, 'Meta') and hasattr(self.Meta, 'ng_models'):
if not isinstance(self.Meta.ng_models, list):
raise TypeError('Meta.ng_model is not of type list')
ng_models = self.Meta.ng_models
else:
ng_models = None
directives = {}
for key in kwargs.keys():
if key.startswith('ng_'):
fmtstr = kwargs.pop(key)
directives[key.replace('_', '-')] = fmtstr
if ng_models is None and 'ng-model' not in directives:
directives['ng-model'] = '%(model)s'
self.prefix = kwargs.get('prefix')
if self.prefix and kwargs.get('data'):
kwargs['data'] = dict((self.add_prefix(name), value) for name, value in kwargs['data'].get(self.prefix).items())
for name, field in self.base_fields.items():
identifier = self.add_prefix(name)
ng = {
'name': name,
'identifier': identifier,
'model': self.scope_prefix and ('%s.%s' % (self.scope_prefix, identifier)) or identifier
}
if ng_models and name in ng_models:
field.widget.attrs['ng-model'] = ng['model']
for key, fmtstr in directives.items():
field.widget.attrs[key] = fmtstr % ng
super(NgModelFormMixin, self).__init__(*args, **kwargs)
def full_clean(self):
"""
Rewrite the error dictionary, so that its keys correspond to the model fields.
"""
super(NgModelFormMixin, self).full_clean()
if self._errors and self.prefix:
self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
def get_initial_data(self):
"""
Return a dictionary specifying the defaults for this form. This dictionary
shall be used to inject the initial values for an Angular controller using
the directive 'ng-init={{thisform.get_initial_data|js|safe}}'.
"""
data = {}
for name, field in self.fields.items():
if hasattr(field, 'widget') and 'ng-model' in field.widget.attrs:
data[name] = self.initial and self.initial.get(name) or field.initial
return data
示例5: NgModelFormMixin
# 需要导入模块: from django.forms.util import ErrorDict [as 别名]
# 或者: from django.forms.util.ErrorDict import items [as 别名]
class NgModelFormMixin(NgFormBaseMixin):
"""
Add this NgModelFormMixin to every class derived from forms.Form, if
you want to manage that form through an Angular controller.
It adds attributes ng-model, and optionally ng-change, ng-class and ng-style
to each of your input fields.
If form validation fails, the ErrorDict is rewritten in a way, so that the
Angular controller can access the error strings using the same key values as
for its models.
"""
def __init__(self, data=None, *args, **kwargs):
self.scope_prefix = kwargs.pop('scope_prefix', getattr(self, 'scope_prefix', None))
if hasattr(self, 'Meta') and hasattr(self.Meta, 'ng_models'):
if not isinstance(self.Meta.ng_models, list):
raise TypeError('Meta.ng_model is not of type list')
ng_models = self.Meta.ng_models
else:
ng_models = None
directives = {}
for key in list(kwargs.keys()):
if key.startswith('ng_'):
fmtstr = kwargs.pop(key)
directives[key.replace('_', '-')] = fmtstr
if ng_models is None and 'ng-model' not in directives:
directives['ng-model'] = '%(model)s'
self.prefix = kwargs.get('prefix')
if self.prefix and data:
data = dict((self.add_prefix(name), value) for name, value in data.get(self.prefix).items())
for name, field in self.base_fields.items():
identifier = self.add_prefix(name)
ng = {
'name': name,
'identifier': identifier,
'model': self.scope_prefix and ('%s.%s' % (self.scope_prefix, identifier)) or identifier
}
if ng_models and name in ng_models:
field.widget.attrs['ng-model'] = ng['model']
for key, fmtstr in directives.items():
field.widget.attrs[key] = fmtstr % ng
try:
if isinstance(data, QueryDict):
data = field.implode_multi_values(name, data.copy())
except AttributeError:
pass
super(NgModelFormMixin, self).__init__(data, *args, **kwargs)
if self.scope_prefix == self.form_name:
raise ValueError("The form's name may not be identical with its scope_prefix")
def _post_clean(self):
"""
Rewrite the error dictionary, so that its keys correspond to the model fields.
"""
super(NgModelFormMixin, self)._post_clean()
if self._errors and self.prefix:
self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
def get_initial_data(self):
"""
Return a dictionary specifying the defaults for this form. This dictionary
shall be used to inject the initial values for an Angular controller using
the directive 'ng-init={{thisform.get_initial_data|js|safe}}'.
"""
data = {}
for name, field in self.fields.items():
if hasattr(field, 'widget') and 'ng-model' in field.widget.attrs:
data[name] = self.initial and self.initial.get(name) or field.initial
return data
def get_field_errors(self, field):
errors = super(NgModelFormMixin, self).get_field_errors(field)
identifier = format_html('{0}.{1}', self.form_name, field.name)
errors.append(SafeTuple((identifier, '$pristine', '$message', 'invalid', '$message')))
return errors
def non_field_errors(self):
errors = super(NgModelFormMixin, self).non_field_errors()
errors.append(SafeTuple((self.form_name, '$pristine', '$message', 'invalid', '$message')))
return errors