Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Api View GET

In my codes, I have a model Tweet, and in tweet_list_view, I want to show the list of tweets as API view.

@api_view(['GET'])
def tweet_list_view(request, *args, **kwargs):
    qs = Tweet.objects.all().order_by('-date_posted')
    serializer = TweetSerializer(data=qs, many=True)
    return Response(serializer.data)

This is what I got as a result.

AssertionError at /tweets/
When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation.
You should either call `.is_valid()` first, or access `.initial_data` instead.

So I called the .is_valid method like following:

@api_view(['GET'])
def tweet_list_view(request, *args, **kwargs):
    qs = Tweet.objects.all().order_by('-date_posted')
    serializer = TweetSerializer(data=qs, many=True)
    if serializer.is_valid():
        return Response(serializer.data, status=201)
    return Response({}, status=400)

Then I get:

TemplateDoesNotExist at /tweets/
rest_framework/api.html

At serializers.py class TweetSerializer(serializers.ModelSerializer): class Meta: model = Tweet fields = ['content', 'date_posted', 'likes']

models.py

class Tweet(models.Model):
    content = models.TextField(blank=True, null=True)
    image = models.FileField(upload_to='images/', blank=True, null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    date_posted = models.DateTimeField(default=timezone.now)
    likes = models.IntegerField(default=0)

    def __str__(self):
        return self.content

    class Meta:
        ordering = ['-date_posted']

It's looking for a template, but it's supposed to use the default Django template. Is there any way to fix this problem?


1 Answers

Update:

forgot the @ in front of the api_view. Added it. Also added the renderer_class (jsonrenderer) to make sure avoiding the error.


You need to use the data attribute of the serializer only when you have a post, put or patch view. In your case just try it without the data attribute and it should be fine

from rest_framework.renderers import JSONRenderer

@api_view(['GET'])
@renderer_classes([JSONRenderer]) 
def tweet_list_view(request, *args, **kwargs): 
    qs = Tweet.objects.all().order_by('-date_posted') 
    serializer = TweetSerializer(qs, many=True)
    return Response(serializer.data)

Here you can see it in the tutorial example of the official django rest framework docs

like image 69
MisterNox Avatar answered Apr 04 '26 06:04

MisterNox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!