Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a 401 Unauthorized in Django?

Tags:

python

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?

like image 802
TIMEX Avatar asked Dec 05 '10 01:12

TIMEX


People also ask

What kind of HTTP response code is 401 unauthorized )?

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.

Why is my 401 unauthorized?

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.

When should I use 401k vs 403?

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.


2 Answers

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.

like image 143
Stu Cox Avatar answered Sep 25 '22 22:09

Stu Cox


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)

like image 26
Wilfred Hughes Avatar answered Sep 24 '22 22:09

Wilfred Hughes