Posted under » Django on 30 Sep 2021
From DRF Serialization II, let us look at the views.py
The imports
from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer
The snippet_list(request). This will list all the existing snippets, or creating a new snippet.
@csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt. This isn't something that you'd normally want to do.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet which is below.
@csrf_exempt def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(status=204)
The URLs part. Create the snippets/urls.py file:
from django.urls import path from snippets import views urlpatterns = [ path('', views.snippet_list), path('<int:pk>/', views.snippet_detail), ]
And finally, the main mysite/urls.py, to include our snippet app's URLs.
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('napi/', include('napi.urls')), path('snippets/', include('snippets.urls')), path('admin/', admin.site.urls), ]
To access the API, you have to go to
Next we learn what does the views' GET, POST and etc do.