170👍
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.
12👍
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
- [Django]-Cannot access django app through ip address while accessing it through localhost
- [Django]-Django: Implementing a Form within a generic DetailView
- [Django]-Using {% url ??? %} in django templates
12👍
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.
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
- [Django]-MySQL vs PostgreSQL? Which should I choose for my Django project?
- [Django]-Django-social-auth django-registration and django-profiles — together
9👍
class HttpResponseUnauthorized(HttpResponse):
def __init__(self):
self.status_code = 401
...
return HttpResponseUnauthorized()
- [Django]-How to implement followers/following in Django
- [Django]-How to test Django's UpdateView?
- [Django]-What is the meaning of bind = True keyword in celery?
3👍
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).
- [Django]-How to make the foreign key field optional in Django model?
- [Django]-Writing a __init__ function to be used in django model
- [Django]-What is the best django model field to use to represent a US dollar amount?