Detect charset from Content-type header in the HttpResponse
|Reported by:||lucky||Owned by:||nobody|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I was surprised today to realize that Django must be configured to instantiate django.http.HttpResponse object.
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from django.http import HttpResponse >>> response = HttpResponse("Hello, World!", content_type="text/plain; charset=iso-8859-1") Traceback (most recent call last): ... ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
This happens because HttpResponse.__init__ reads settings.DEFAULT_CHARSET to fill the property self._charset. It is assumed charset of the response content. This is always taken from the settings even if content_type has passed as parameter and contains the charset.
In addition, this behavior breaks the django.test.TestCase.assertContains() when encoding of response content differs from the settings.DEFAULT_CHARSET.
This patch makes HttpResponse object to fill self._charset property with value from content_type argument if given.
Change History (5)
Changed 4 years ago by lucky
comment:1 Changed 4 years ago by russellm
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted