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?
The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.
The 401 Unauthorized error is an HTTP status code that means the page you were trying to access cannot be loaded until you first log in with a valid user ID and password. If you've just logged in and received the 401 Unauthorized error, it means that the credentials you entered were invalid for some reason.
401 Unauthorized is the status code to return when the client provides no credentials or invalid credentials. 403 Forbidden is the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With