How do I return a 401 Unauthorized in Django?
Instead of doing this:
res = HttpResponse("Unauthorized")
res.status_code = 401
return res
Is there a way to do it without typing it every time?
I know this is an old one, but it's the top Google result for "django 401", so I thought I'd point this out...
Assuming you've already imported django.http.HttpResponse
, you can do it in a single line:
return HttpResponse('Unauthorized', status=401)
The 'Unauthorized'
string is optional. Easy.
class HttpResponseUnauthorized(HttpResponse):
status_code = 401
...
return HttpResponseUnauthorized()
Normally, you should set the instance in __init__
or you end up with class variables that are shared between all instances. However, Django does this for you already:
class HttpResponse(object):
"""A basic HTTP response, with content and dictionary-accessed headers."""
status_code = 200
def __init__(self, content='', mimetype=None, status=None,
content_type=None):
# snip...
if status:
self.status_code = status
(see the Django code in context)
Inheritance solution
from django.http import HttpResponse
class Http401(HttpResponse):
def __init__(self):
super().__init__('401 Unauthorized', status=401)
in a util.py
to replace multiple calls to:
return HttpResponse('401 Unauthorized', status=401)
with just:
return Http401()
Interestingly there are other named responses in 1.9.6 https://github.com/django/django/blob/1.9.6/django/http/response.py#L443 but not 401.
class HttpResponseUnauthorized(HttpResponse):
def __init__(self):
self.status_code = 401
...
return HttpResponseUnauthorized()
Write a view decorator that checks the appropriate HTTP headers and returns the appropriate response (there is no built-in type for response code 401).