Hello dear stack overflowers, I've set up a Django project with restful framework and I use JSON response in order to retrieve data from the server in a structured manner.
models.py
class Container(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=False, default='content')
content = models.TextField()
class Meta:
ordering = ['created']
The problematic code:
views.py
class ContentView(RetrieveAPIView):
queryset = Container.objects.all()
serializer_class = ContainerSerializer
def get_object(self):
queryset = self.get_queryset()
serializer = ContainerSerializer(queryset,many=True)
return JsonResponse(serializer.data , safe=False)
Gives the following error when being executed:
AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `ContainerSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `JsonResponse` instance.
Original exception text was: 'JsonResponse' object has no attribute 'title'.
[21/May/2021 17:27:13] "GET /content/ HTTP/1.1" 500 18789
To be as clear as possible I'll attach the serializer's code:
serializers.py
class ContainerSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=True, allow_blank=False, max_length=100)
content = serializers.CharField()
def create(self, validated_data):
return Container.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.content = validated_data.get('content', instance.content)
instance.save()
return instance
Before switching to RetrieveAPIView, everything worked well with the test server. The error arised while switching to this new-for-me method of making requests.
Any help will be appreciated!