Codewizard_26
Codewizard_26

Reputation: 68

AssertionError at /wel/ Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneTyp

I am trying to create an api using django rest framework but facing the above mentioned issue

my models.py code

from django.db import models

class React(models.Model):
    name=models.CharField(max_length=20)
    details=models.CharField(max_length=500)

and my views.py code

from django.shortcuts import render
from rest_framework.views import APIView
from . models import *
from rest_framework.response import Response
from . serializer import *


class ReactView(APIView):
    serializer_class = ReactSerializer
    def get(self,request):
        for detail in React.objects.all():
            detail = [{'name':detail.name,'detail':detail.detail}]
            return Response(detail)
        


    def post(self,request):
        serializer=ReactSerializer(data=request.data)
        if serializer.is_valid(raise_exception = True):
            serializer.save()

Upvotes: 0

Views: 702

Answers (1)

Henrique Andrade
Henrique Andrade

Reputation: 991

If React.objects.all() is empty, the get method will return None and this error will be raised. Just add return Response({}, status.HTTP_204_NO_CONTENT) to this method, or anything that makes sense to you application.

from rest_framework import status

class ReactView(APIView):
    serializer_class = ReactSerializer
    def get(self,request):
        for detail in React.objects.all():
            detail = [{'name':detail.name,'detail':detail.detail}]
            return Response(detail)
        return Response({}, status.HTTP_204_NO_CONTENT)

Upvotes: 1

Related Questions