57👍
You can access them within a view using request.META
, which is a dictionary.
If you wanted the Authorization header, you could do request.META['HTTP_AUTHORIZATION']
If you’re creating a restful API from scratch, you might want to take a look at using tastypie.
14👍
As of django 2.2 HttpRequest.headers
were added to allow simple access to a request’s headers. So now you can also get authentication header using get()
function on request.headers
request.headers.get('Authorization')
This will give you value token value back.
Bearer eyJ0eYourToken...
https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpRequest.headers
- [Django]-Explicitly set MySQL table storage engine using South and Django
- [Django]-CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
- [Django]-How to set the default of a JSONField to empty list in Django and django-jsonfield?
10👍
You can use
request.META['HTTP_AUTHORIZATION']
and sometimes
request.META['Authorization']
can help.
- [Django]-Django project base template
- [Django]-How to rename items in values() in Django?
- [Django]-How do I access the request object or any other variable in a form's clean() method?
1👍
For older versions of django prior to 2.2, you’ll need to access the headers in the following way using the META key. Always important to first check if the key authorization header keys exists just in case it wasn’t posted otherwise you’ll run into non-existent key errors.
if not ('HTTP_AUTHORIZATION' in request.META.keys()):
return HttpResponse('NO AUTH HEADER PROVIDED')
elif (request.META['HTTP_AUTHORIZATION'] == 'Bearer YourAuthorizationKey123':
# Validation passed - Proceed with whatever else you want to do
- [Django]-No module named urllib.parse (How should I install it?)
- [Django]-Django select only rows with duplicate field values
- [Django]-Database returned an invalid value in QuerySet.dates()
0👍
HttpRequest.headers
New in Django 2.2.
if 'Authorization' in request.headers: # Authorization header exists
#do something here
pass
else: # Authorization header not exists
#do something here
pass
Read also Django official Doc
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-How do I retrieve a Django model class dynamically?
- [Django]-Check if model field exists in Django