I’m trying to organize error messages that are returned by my django application, and am having problems with subclasses of HttpResponseBadRequest objects having empty content:
In views.py:
class HttpNoContentAvailable(django.http.HttpResponseBadRequest):
content = "Must add content before making this request."
def get_content(request, project_id):
project = Project.objects.get(pk=project_id)
if not project.has_content():
return HttpNoContentAvailable()
...
It works the following:
def get_content(request, project_id):
project = Project.objects.get(pk=project_id)
if not project.has_content():
return HttpNoContentAvailable("Must add content before making this request.")
...
In my application, there are many views that need to return the same 400 response depending on whether or not there is content, and I’d like to keep the response content stored in one place. To make matters more “interesting,” my unit tests running on the development server pass — I get HTTP 400 responses with the correct content, but when running in production I get HTTP 400 responses with no content.
How can I get the HTTP 400 response to have the correct content? (or, more generally, how would you suggest I organized the code to accomplish the goal of only having the response content stored once?)
You should override the constructor in your subclass instead of defining content as a class variable.
For example: