django & django rest framework - noteman1/wiki GitHub Wiki

create django project

$ mkdir my_project
$ cd my_project
$ python3 -m venv .venv
$ source .venv/bin/activate
$ python -m pip install -U pip wheel
$ pip install django djangorestframework
$ django-admin startproject my_project .
$ python manage.py startapp app
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

CORS

$ pip install django-cors-headers
INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

setup to use token

settings.py

INSTALLED_APPS = [
    ...
    'rest_framework.authtoken',
    ...
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}
$ python manage.py migrate

create token

1. ObtainAuthToken view

from rest_framework.authtoken.views import obtain_auth_token
from django.urls import path

urlpatterns = [
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]

POST api-token-auth/

2. by program

from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User

user = User.objects.get(username='username')
token = Token.objects.create(user=user)
print(token.key)

using token on the client

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

request a token on the view of drf

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class DetailView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    
    def get(self, request, format=None):
        content = {
            'user': str(request.user),
            'auth': str(request.auth),
        }
        return Response(content)