Skip to content

Commit

Permalink
Reworked ErrorDict.as_json() to prevent unnecessary serialization/des…
Browse files Browse the repository at this point in the history
…erialization step.

Thanks @apollo13 for the suggestion. Refs #17413.
  • Loading branch information
loic authored and apollo13 committed Mar 6, 2014
1 parent 9b729dd commit 34236ef
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions django/forms/utils.py
Expand Up @@ -4,6 +4,11 @@
import sys import sys
import warnings import warnings


try:
from collections import UserList
except ImportError: # Python 2
from UserList import UserList

from django.conf import settings from django.conf import settings
from django.utils.html import format_html, format_html_join, escape from django.utils.html import format_html, format_html_join, escape
from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.encoding import force_text, python_2_unicode_compatible
Expand All @@ -15,11 +20,6 @@
# module to maintain backwards compatibility. # module to maintain backwards compatibility.
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError


try:
from collections import UserList
except ImportError: # Python 2
from UserList import UserList



def flatatt(attrs): def flatatt(attrs):
""" """
Expand Down Expand Up @@ -56,8 +56,7 @@ def as_data(self):
return {f: e.as_data() for f, e in self.items()} return {f: e.as_data() for f, e in self.items()}


def as_json(self, escape_html=False): def as_json(self, escape_html=False):
errors = {f: json.loads(e.as_json(escape_html=escape_html)) for f, e in self.items()} return json.dumps({f: e.get_json_data(escape_html) for f, e in self.items()})
return json.dumps(errors)


def as_ul(self): def as_ul(self):
if not self: if not self:
Expand All @@ -84,17 +83,20 @@ class ErrorList(UserList, list):
A collection of errors that knows how to display itself in various formats. A collection of errors that knows how to display itself in various formats.
""" """
def as_data(self): def as_data(self):
return self.data return ValidationError(self.data).error_list


def as_json(self, escape_html=False): def get_json_data(self, escape_html=False):
errors = [] errors = []
for error in ValidationError(self.data).error_list: for error in self.as_data():
message = list(error)[0] message = list(error)[0]
errors.append({ errors.append({
'message': escape(message) if escape_html else message, 'message': escape(message) if escape_html else message,
'code': error.code or '', 'code': error.code or '',
}) })
return json.dumps(errors) return errors

def as_json(self, escape_html=False):
return json.dumps(self.get_json_data(escape_html))


def as_ul(self): def as_ul(self):
if not self.data: if not self.data:
Expand Down

0 comments on commit 34236ef

Please sign in to comment.