diff --git a/django/http/response.py b/django/http/response.py index a317f96eb48..ce6b0344a73 100644 --- a/django/http/response.py +++ b/django/http/response.py @@ -102,6 +102,9 @@ class HttpResponseBase(six.Iterator): """ if not isinstance(value, (bytes, six.text_type)): value = str(value) + if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or + isinstance(value, six.text_type) and ('\n' in value or '\r' in value)): + raise BadHeaderError("Header values can't contain newlines (got %r)" % value) try: if six.PY3: if isinstance(value, str): @@ -124,8 +127,6 @@ class HttpResponseBase(six.Iterator): else: e.reason += ', HTTP response headers must be in %s format' % charset raise - if str('\n') in value or str('\r') in value: - raise BadHeaderError("Header values can't contain newlines (got %r)" % value) return value def __setitem__(self, header, value): diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index da371dc74ba..25da7b622c7 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -306,6 +306,9 @@ class HttpResponseTests(unittest.TestCase): f = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88'.encode('latin-1') f = f.decode('utf-8') h['Content-Disposition'] = 'attachment; filename="%s"' % f + # This one is triggering http://bugs.python.org/issue20747, that is Python + # will itself insert a newline in the header + h['Content-Disposition'] = 'attachement; filename="EdelRot_Blu\u0308te (3)-0.JPG"' def test_newlines_in_headers(self): # Bug #10188: Do not allow newlines in headers (CR or LF)