django-rest-framework accept JSON data?

You have missed adding the Content-Type header in the headers section. Just set the Content-Type header to application/json and it should work. See the below image: Also, you might also need to include a CSRF token in the header in case you get an error {“detail”: “CSRF Failed: CSRF token missing or incorrect.”} while making … Read more

Django REST Exceptions

The Django REST framework provides several built in exceptions, which are mostly subclasses of DRF’s APIException. You can raise exceptions in your view like you normally would in Python: from rest_framework.exceptions import APIException def my_view(request): raise APIException(“There was a problem!”) You could also create your own custom exception by inheriting from APIException and setting status_code … Read more

How do you return 404 when resource is not found in Django REST Framework

Simply way to do it, you can use raise Http404, here is your views.py from django.http import Http404 from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from yourapp.models import Snippet from yourapp.serializer import SnippetSerializer class SnippetDetailView(APIView): def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 def get(self, request, pk, format=None): … Read more

AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context

You’re getting this error as the HyperlinkedIdentityField expects to receive request in context of the serializer so it can build absolute URLs. As you are initializing your serializer on the command line, you don’t have access to request and so receive an error. If you need to check your serializer on the command line, you’d … Read more

Django Rest Framework Read Only Model Serializer

You really want to do this at the view (or Viewset) level, which you can do with a ReadOnlyModelViewSet. (You mentioned this in your comment but I’m leaving it as an answer for better visibility). For example (from the documentation): from rest_framework import viewsets class AccountViewSet(viewsets.ReadOnlyModelViewSet): “”” A simple ViewSet for viewing accounts. “”” queryset … Read more