27
loading...
This website collects cookies to deliver better user experience
'Authorization' : 'Token 622af924b5e828dd35dd6'
const token = 'YOUR_TOKEN_HERE';
const response = await fetch('api/posts/3', {
method: 'DELETE',
headers: {
Authorization: `Token ${token}`
},
});
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
class UserLoginApiView(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PostViewSet, UserLoginApiView
router = DefaultRouter()
router.register('posts', PostViewSet)
urlpatterns = [
path('', include(router.urls)),
path('login/', UserLoginApiView.as_view()),
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'posts',
'rest_framework.authtoken',
]
python manage.py migrate
python manage.py runserver
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.user.id == request.user.id
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import Post
from .serializers import PostSerializer
from .permissions import UpdateOwnProfile
class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (
UpdateOwnProfile,
IsAuthenticatedOrReadOnly,
)
queryset = Post.objects.all()
{
"username": "ericthecoder",
"password": "yourpassword"
}
{
"title": "My First Blog Title",
"body": "My first Blog body Content",
"user": 1
}
POST api/login/ (login with credentials)
GET api/posts (Read all post)
POST api/posts/ (Create a new post)
GET api/posts/1/ (Read a specific Post)
PUT api/posts/1/ (Update a specific Post)
PATCH api/posts/1/ (Partial Update a specific Post)
DELETE api/posts/1/ (Delete a specific Post)