Click here to Skip to main content
15,667,536 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
<pre lang="Python"><pre>from django.http.response import JsonResponse
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework import serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import PostSerializer
from .models import Post,categories
from rest_framework.views import APIView

# Create your views here.
@api_view(['GET'])
def apiOverview(request):
    api_urls={
        'List':'/article-list/',
        'Detail View':'/article-detail/<str:pk>/',
        'Create':'/article-create/',
        'Update':'article-update/<str:pk>/',
        'Delete':'/article-delete/<str:pk>/',
    }
    return Response(api_urls)

@api_view(['GET'])
def articleList(request):
    articles=Post.objects.all()
    serializers=PostSerializer(articles,many=True)
    return Response(serializers.data)

@api_view(['GET'])
def articleDetail(request,pk):
    articles=Post.objects.get(id=pk)
    serializers=PostSerializer(articles,many=False)
    return Response(serializers.data)

@api_view(['POST'])
def articleCreate(request):
    serializers=PostSerializer(data=request.data)
    if serializers.is_valid():
        serializers.save()
    return Response(serializers.data)

@api_view(['POST'])
def articleUpdate(request,pk):
    articles=Post.objects.get(id=pk)
    serializers=PostSerializer(instance=articles,data=request.data)

    if serializers.is_valid():
        serializers.save()
    return Response(serializers.data)

@api_view(['DELETE'])
def articleDelete(request, pk):
    articles=Post.objects.get(id=pk)
    articles.delete()
    return Response('The item has been deleted')


What I have tried:

I am a beginner learning the Django RestFramework. I had created this for an blog post page for my project. I looked through different tutorials and posts but couldn't really figure out. Can you help me converting this functional view into a class view? Thanks
Posted
Updated 15-Jun-21 3:53am

1 solution

See the example on the front page of the Django website: Home - Django REST framework[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900